2013-02-18 78 views
-4

我学习的冒泡排序算法,我碰到贯彻它,我的问题是,这是更好,为什么2种方式?冒泡排序算法实现

for(k=0;k<array.length-1;k++){ 
      if(array[k] > array[k+1]){ 
       int temp = array[k]; 
       array[k] = array[k+1]; 
       array[k+1] = temp; 
      } 
     } 

第二比约其

for(i=array.length-1;i>=0;i--){ 
     for(k=0;k<i;k++){ 
      if(array[k] > array[k+1]){ 
       int temp = array[k]; 
       array[k] = array[k+1]; 
       array[k+1] = temp; 
      } 
     } 
     } 
+4

第一个不会对数组进行排序。 – sgarizvi 2013-02-18 11:08:12

+2

第二个更好,因为它对给定的数组进行排序。 – 2013-02-18 11:16:47

回答

1

更多孰优孰劣 - 其所有关于这一个排在阵列第一和答案是第二届一个

检查this获得更多的想法

0

你实现第一次没有使正确排序becouse算法可以切换仅2相邻的元素。

Ex。

输入数据{6,5,4,3,2}

第一次迭代使这 - > {5,6,4,3,2}和现在5是第一位置,并且没有机会改变这一立场,becouse循环索引(k)为1,而进一步的迭代会增加..

冒泡排序需要2路总是

public static void bubbleSort(int[] array){ 
    for (int i = 0; i < array.length - 1; i++) { 
     for (int j = 0; j < array.length - i - 1; j++) { 
      if(array[j] < array[j+1]){ 
       int tmp = array[j]; 
       array[j] = array[j+1]; 
       array[j+1] = tmp; 
      } 
     } 
    } 
} 
0

我发现更高效的维基百科(http://en.wikipedia.org/wiki/Bubble_sort

procedure bubbleSort(A : list of sortable items) 
    n = length(A) 
    repeat 
     newn = 0 
     for i = 1 to n-1 inclusive do 
      if A[i-1] > A[i] then 
      swap(A[i-1], A[i]) 
      newn = i 
      end if 
     end for 
     n = newn 
    until n = 0 
end procedure 
0

第二个将数组进行排序。但是,只有在上次迭代中至少有一次交换时,才可以通过运行来减少第二次循环中的比较。

+0

这样你可以减少最好的情况下的复杂性。 – 2014-03-05 16:38:44

0

你的第一个解决方案将无法工作,它不会对数组进行排序。但第二个方法会起作用,它会将数据从最小到最大排序。有关详细说明,请参见下文:

嘛,后面冒泡排序算法的想法是要经过数据的阵列/集,而比较每对相邻的项目,并交换他们,如果他们是在错误的顺序。重复传递数组/列表直到不需要交换,这表明列表/数组已排序。 时间复杂度:为O(n^2)。和我们将使用原始数组的空间。请使用以下数组说明上述段落中的说明:

//array of integer to be sorted 
    int[] arrayToSort=new int[]{1,7,81,2,-2,9,9,6,-6}; 
    //repeat until we're done sorting 
    while (true){ 
     //flag to check if we did swap number(s) 
     boolean didSort=false; 
     /* 
     * this inner loop is being used to find numbers that need to be  
     * swapped and then help in swapping them 
     */ 
     for(int count=0;count<arrayToSort.length-1;count++){ 
      //check if we need to swap 
      if(arrayToSort[count]>arrayToSort[count+1]){ 
       int temp=arrayToSort[count+1]; 
       arrayToSort[count+1]=arrayToSort[count]; 
       arrayToSort[count]=temp; 
       //set our swap flag so that we will know that we did swap 
       didSort=true; 
      } 

     } 

     //check we did a swap in our last inner loop iteration if not will 
     //be done sorting, then break the outer loop 
     if(!didSort){ 
      break; 
     } 
    } 

    //let's print the sorted array. 
    for(int i=0;i<arrayToSort.length;i++){ 
     System.out.print(arrayToSort[i]+", "); 
    } 
+0

虽然这是一个答案,可否扩展一下? http://stackoverflow.com/help/how-to-answer – 2016-06-13 14:05:05