Optimized Bubble Sort (Java)

前端 未结 10 1211
旧时难觅i
旧时难觅i 2020-12-05 11:29

I would like to know how else I can optimize bubble sort so that it overlooks elements that have already been sorted, even after the first pass.

Eg. [4, 2, 3         


        
10条回答
  •  鱼传尺愫
    2020-12-05 12:15

    In the above example, the array got sorted after 3rd pass, but we will still continue with the 4th, 5th pass. Suppose if the array is already sorted, then there will be no swapping (because adjacent elements are always in order), but still we will continue with the passes and there will still be (n-1) passes.

    If we can identify, that the array is sorted, then we should stop execution of further passes. This is the optimization over the original bubble sort algorithm.

    If there is no swapping in a particular pass, it means the array has become sorted, so we should not perform the further passes. For this we can have a flag variable which is set to true before each pass and is made false when a swapping is performed.

    void bubbleSort(int *arr, int n){
    for(int i=0; iarray[j+1])
          {
            flag = true;
             int temp = array[j+1];
             array[j+1] = array[j];
             array[j] = temp;
          }
       }
      // No Swapping happened, array is sorted
      if(!flag){ 
         return; 
      }}}
    

提交回复
热议问题