Two ways to write bubble sort

int[] array = new int[]{5,1,3,9,4,8,7,0,6,2};

1. Ordinary bubble sort

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

2. Bubble sort that is easier to write [recommended]

for (int i = 0; i < array.length; i++) {
  for (int j = 0; j < i; j++) {
    if (array[i] < array[j]) {
      int temp = array[i];
      array[i] = array[j];
      array[j] = temp;
    }
  }
}

 

Guess you like

Origin blog.csdn.net/chenzhengfeng/article/details/105657477