Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 7th, 2012  |  syntax: None  |  size: 1.84 KB  |  hits: 22  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. insertion sort algorithm flaw in java code
  2. public void insertionSort(){
  3.     int key;
  4.     int i;  
  5.     for ( int j = 0; j < this.a.length; j++ ){
  6.         key = a[j];
  7.         i = j - 1;
  8.  
  9.         while ( i > 0 && a[i] > key ){
  10.         a[i + 1] = a[i];
  11.         i = i - 1;
  12.         }
  13.         a[i+1] = key;
  14.     }
  15. }
  16.        
  17. jan@janspc:~/Dropbox/programming/java/algorithms$ vim sort.java
  18. jan@janspc:~/Dropbox/programming/java/algorithms$ javac sort.java
  19. jan@janspc:~/Dropbox/programming/java/algorithms$ java Test
  20. 49, 68, 60, 14, 70, 8, 83, 96, 29, 7, 92, 35, 17, 84, 31, 62, 48, 95, 16, 22, 31, 97, 72, 55, 88, 63, 1, 63, 96, 32, 74, 15, 92, 77, 50, 13, 12, 36, 90, 93, 20, 15, 67, 88, 23, 31, 95, 90, 86, 65, 35, 27, 60, 4, 90, 11, 22, 97, 65, 88, 23, 1, 25, 21, 9, 81, 87, 56, 2, 4, 63, 52, 55, 86, 62, 30, 55, 64, 19, 10, 45, 92, 87, 43, 39, 95, 20, 43, 3, 30, 74, 64, 4, 90, 91, 93, 94, 44, 87, 21,
  21.  
  22. 49, 1, 1, 2, 3, 4, 4, 4, 7, 8, 9, 10, 11, 12, 13, 14, 15, 15, 16, 17, 19, 20, 20, 21, 21, 22, 22, 23, 23, 25, 27, 29, 30, 30, 31, 31, 31, 32, 35, 35, 36, 39, 43, 43, 44, 45, 48, 50, 52, 55, 55, 55, 56, 60, 60, 62, 62, 63, 63, 63, 64, 64, 65, 65, 67, 68, 70, 72, 74, 74, 77, 81, 83, 84, 86, 86, 87, 87, 87, 88, 88, 88, 90, 90, 90, 90, 91, 92, 92, 92, 93, 93, 94, 95, 95, 95, 96, 96, 97, 97,
  23.  
  24. Executon took: 110628 nano sek?
  25.        
  26. while ( i >= 0 && a[i] > key ){
  27.        
  28. public void insertionSort(){
  29.    int key;
  30.    int i;  
  31.    for ( int j = 1; j < this.a.length; j++ ){
  32.        key = a[j];
  33.        i = j;
  34.  
  35.        while ( i > 0 && a[i-1] > key ){
  36.        a[i] = a[i-1];
  37.        i = i - 1;
  38.        }
  39.        a[i] = key;
  40.     }
  41. }
  42.        
  43. key = A[j]>
  44. i = j-1
  45. while i>0 && A[i]>key
  46.     A[i+1] = A[i]
  47.     i = i-1
  48. A[i+1] = key
  49.        
  50. for ( int j = 1; j < this.a.length; j++ ){
  51.     key = a[j];
  52.     i = j - 1;
  53.  
  54.     while ( i > 0 && a[i] > key ){
  55.     a[i + 1] = a[i];
  56.     i = i - 1;
  57.     }
  58.     a[i+1] = key;
  59. }