Credits

Saturday, February 28, 2009

Java Sorting Program using Array

Sorting is a technique to arrange elements in a pattern or orderly manner. Various sorting techniques can be applied. However, if elements are in bigger number, these sorting techniques may show a distinguishing difference from one another.

Sorting techniques can be bubble sort, selection sort, insertion sort, heap sort, merge sort and quick sort.

But bubble sort can be implemented through Java. Check the program below.



[+/-] show/hide




//program to bubble sort
class onedarray{
public static void main (String [] args){
int sample[]={99,-10,100123,18,-978,5623,463,-9,287,49};
int i,a,b,t;
int size=10;
System.out.print("\nThe unsorted array elements are ");
for(i=0;i<10;i++)
System.out.print(" "+sample[i]);

//sorting technique
for(a=1;\ /*concatenate the next line*/
a

for (b=size-1;b>=a;b--){
if (sample[b-1]>sample[b]){
//if out of order
//exchange elements
t=sample[b-1];
sample[b-1]=sample[b];
sample[b]=t;
}
}

System.out.print("\nThe sorted array elements are ");
for(i=0;i<10;i++)
System.out.print(" "+sample[i]);
}
}

AddThis