两两相比较,大的放后面,小的放前面。以升序为例:
从第0个数开始,将相邻两个位置的数据进行比较,如果后面的数据小于前面的数据,则交换他们的位置,最后最大的数会放在数据的末尾。时间复杂度为O(n^2),空间复杂度为O(1)。
int[] array = {80, 90, 50, 100, 1, 8, 6, 75};int temp = 0;for (int i = 0; i < array.length - 1; i++) {for (int j = 0; j < array.length - 1 - i; j++) {if (array[j] > array[j + 1]){temp = array[j];array[j] = array[j + 1];array[j + 1] = temp;}}}System.out.println(Arrays.toString(array));
