InsertionSort
Insertion sort is a simple sorting algorithm which is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort.
<Introduction to algorithm>
Insertion sort works the way many people sort a hand of
playing cards. We start with an empty left hand and the cards face down on the
table. We then remove one card at a time from the table and insert it into the
correct position in the left hand. To find the correct position for a card, we compare
it with each of the cards already in the hand, from right to left, as illustrated in
Figure 2.1. At all times, the cards held in the left hand are sorted, and these cards
were originally the top cards of the pile on the table.
1 /* 2 * Best Average Worst Memory Stable 3 * n n^2 n^2 1 Yes 4 */ 5 public class InsertionSort { 6 7 public static void sort(int[] a){ 8 for(int j = 1; j < a.length; j++){ 9 int key = a[j]; 10 int i = j-1; 11 while(i >= 0 && a[i] > key){ 12 a[i+1] = a[i]; 13 a[i] = key; 14 i--; 15 } 16 } 17 } 18 public static void printArray(int[] a){ 19 for(int i = 0;i < a.length;i++){ 20 System.out.print(a[i]+" "); 21 } 22 } 23 24 public static void main(String[] args) { 25 // TODO Auto-generated method stub 26 int[] a={5,1,3,4,0,9}; 27 sort(a); 28 printArray(a); 29 } 30 31 }
浙公网安备 33010602011771号