Array5
By the end of this lesson, you will
be able to:
Understand sort algorithm
Sort algorithm
Sort algorithm is an algorithm that orders
the elements of a list in a certain order
(Ascending or Descending).
The process of sorting code is based on
the idea of comparing one element with
the next element of the array each time,
and swapping them if needed, and so on.
A Java program that sorts the
elements of array in ascending
double marathon_time[] order.
={11.45,11.40,
13.24, 10.50};
int i,j;
double temp;
for (i = 0; i<4 ; i++ ){
for (j=i+1; j<4; j++){
if (marathon_time[i]>marathon_time[j]){
temp = marathon_time[i];
marathon_time[i]=marathon_time[j];
marathon_time[j]=temp;
} } }
for (i=0; i<4 ; i++)
[Link] (marathon_time[i]+ \t);
} }
Practical Activity Page 115
1. Create a program that reads 10 numbers
integers numbers, save them in an array and
sorts the numbers in descending order. Your
program prints the elements before and after
the sort.
An
s: int i, j, temp;
int items[] = new int[10];
Scanner inputdata = new Scanner([Link]);
for (i=0; i<10 ; i++) {
[Link]("Enter Array Element No " + i + " = ");
items[i] = [Link](); }
[Link]("Array Element Befor sorting = ");
for (i=0; i<10 ; i++) {
[Link] (items[i]+ "\t"); }
for (i = 0; i<10 ; i++ ) {
for (j=i+1; j<10; j++) {
if (items[i]<items[j]) {
temp = items[i];
items[i]=items[j];
items[j]=temp; } } }
[Link]("\n Array Element After sorting = ");
for (i=0; i<10 ; i++)
[Link] (items[i]+ "\t"); } }
Howe Work:
Assessment Page
116
int arraySize,i;
Scanner inputdata = new Scanner([Link]);
[Link]("Enter the letters no. of your name: ");
arraySize = [Link]();
[Link]();
char items[] = new char[arraySize];
char temp;
for (i=0; i<arraySize ; i++)
{
[Link]("Enter Letter No " + i + " = ");
items[i] = [Link]().charAt(0);
}
[Link]("Name Befor sorting : ");
for (i=0; i<arraySize ; i++)
{
[Link] (items[i]+ " ");
}
int j;
for (i = 0; i<arraySize ; i++ )
{
for (j=i+1; j<arraySize; j++){
if (items[i]<items[j]){
temp = items[i];
items[i]=items[j];
items[j]=temp;
} } }
[Link]("\nName After sorting
Ascending : ");
for (i=0; i<arraySize ; i++)
[Link] (items[i]+ " ");
[Link]("\nName After sorting
Descending : ");
for (i=arraySize-1; i> -1 ; i--)
[Link] (items[i]+ " ");
}
}