Optimized Bubble Sort (Java)

前端 未结 10 1203
旧时难觅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:29

    I think this is what you need. The key is to consider the array only till the index where last swap occured(newn).

    public static void bubblesort(int[] a) {
      int i, n, newn;
      n = a.length;
    
      while (n > 0) {
          newn = 0;
          for (i = 1; i < n; i++) {
              if (a[i - 1] > a[i]) {
                  temp = a[i];
                  a[i] = a[i - 1];
                  a[i - 1] = temp;
                  newn = i;
              }
          }
          n = newn;
        }
    
        return a;
    }
    
    

提交回复
热议问题