排序算法的学习

xiaoxiao2021-02-28  14

排序:将“无序”的序列调整为“有序”的序列。 1.冒泡排序(从后往前): 比较相邻的元素,较大的放置后一位,在与之后的相比较,一次类推,到最后,最后一个元素为最大的元素。然后循环,排出序列。

实例学习: public class BubbleSort { public static void main(String[] args) { int[] intArray = { 3, 8, 3, 5, 6, 2, 1, 55, 74 }; bobble(intArray); } public static void bobble(int[] intArray) { for (int i = 0; i < intArray.length - 1; i++) { for (int j = 0; j < intArray.length - i - 1; j++) { if (intArray[j] > intArray[j + 1]) { compare(intArray, j, j + 1); } } } bubbling(intArray); } public static void bubbling(int[] intArray) { for (int i = 0; i < intArray.length; i++) { System.out.print(intArray[i] + ","); } } public static void compare(int[] intArray, int i, int j) { int temp = 0; temp = intArray[i]; intArray[i] = intArray[j]; intArray[j] = temp; } } 运行结果: 1,2,3,3,5,6,6,8,55,74,

2.简单选择排序: 先找出最小(大)元素,放置序列起始位置,然后依次剩余未排序元素中寻找最小(大)元素,最后一元素放到已排序序列的末尾,排序完毕。

public class Selection_sort { public static void main(String[] args) { int[] intArray = { 3, 8, 3, 5, 6, 2, 1, 55, 74 }; choose(intArray); } public static void choose(int []intArray){ for (int i = 0; i < intArray.length - 1; i++) { for (int j = i+1; j < intArray.length ; j++) { if(intArray[j]<intArray[i]){ compare(intArray, i, j); } } } selection(intArray); } public static void selection(int[] intArray) { for (int i = 0; i < intArray.length; i++) { System.out.print(intArray[i] + ","); } } public static void compare(int[] intArray, int i, int j) { int temp = 0; temp = intArray[i]; intArray[i] = intArray[j]; intArray[j] = temp; } } 运行结果: 1,2,3,3,5,6,6,8,55,74,

每档一语: 人的一生,可以有所作为的时机只有一次,那就是现在。

转载请注明原文地址: https://www.6miu.com/read-2350188.html

最新回复(0)