// The Insertion Sort is normally the best of
// the elementary sorts. Unlike the other sorts that
// had a group sorted at any given time, groups are
// only partially sorted here.
//The complexity of insertion sorting is O(n) for best case (already sorted array) and O(n2) for //worst case (sorted in reverse order).
import java.io.*;
// the elementary sorts. Unlike the other sorts that
// had a group sorted at any given time, groups are
// only partially sorted here.
//The complexity of insertion sorting is O(n) for best case (already sorted array) and O(n2) for //worst case (sorted in reverse order).
import java.io.*;
class InsertionSortTest {
public static void main (String[] args) {
int[] a={5,2,9,1,23};
// ascending order
int j=i;
int valueToStore=a[i];
while(j>0 && a[j-1] > valueToStore){
a[j]=a[j-1];
j--;
}
a[j] = valueToStore;
}
System.out.print(" "+a[i]);
}
System.out.println(" ");
// descending order
for(int i=0;i <a.length;i++)
int j=i;
int valueToStore=a[i];
while(j>0 && a[j-1] < valueToStore){
a[j]=a[j-1];
j--;
}
a[j] = valueToStore;
}
System.out.print(" "+a[i]);
}
}
}
Comments
Post a Comment