2012-09-08 29 views
0

此代碼排序正確。這是插入排序嗎?我的代碼是插入排序的正確實現嗎?

import java.util.Scanner; 
public class InsertionSort { 

    public static void main(String[] args) { 
     Scanner sc = new Scanner(System.in); 
     System.out.println("Enter the number of elements: "); 
     int count; 
     count = sc.nextInt(); 
     int[] a = new int[count]; 
     System.out.println("Enter elements: "); 
     for(int i = 0 ; i<count;i++){ 
      a[i] = sc.nextInt(); 
     } 
     int j,temp; 
     System.out.println("aftr insertion sort :"); 
     for(int i = 1 ; i<count;i++){ 
      j=i; 
      while(j>0 && a[j-1] > a[j]){ 
       temp = a[j]; 
       a[j] = a[j-1]; 
       a[j-1] = temp; 
       j--; 
      } 
     } 
     for(int i = 0 ; i<count;i++){ 
      System.out.print(a[i]+" "); 
     } 
    } 
} 
+7

我已經爲您正確縮進代碼,這使得它稍微容易閱讀:)您可以使用此網站自動執行此操作:http://www.prettyprinter.de/ – Wolph

+4

編寫測試並測試它,我們不是編譯器:) – Drakosha

+1

如果它符合[算法的定義](http://en.wikipedia.org/wiki/Insertion_sort#Algorithm),那麼是的... – Miguel

回答

2

我重點介紹三個for環路的第二,一個地方的實際排序發生。這個循環對我來說看起來很好。