冒泡排序和选择排序区别

冒泡排序和选择排序区别 1.稳定性 冒泡排序稳定排序。(例如 1,2,3,2,4 排完序后两个2,2 先后顺序不变) 选择排序不稳定排序。

2.都属于比较排序,交换成本不同。 冒泡排序需要相邻元素比较,如果当前元素大于后一个元素进行交换。 选择排序,先选择后交换,减少交换次数。

import java.util.Arrays; /** * @program:tpb * @description:冒泡排序 比较相邻的元素。如果第一个比第二个大,就交换他们两个,稳定排序 * @author:heshuangxi * @create:2020-06-30 19:29 **/ public class BubbleSort { public int[] sort(int[] sourceArray) { //遍历数组长度-1遍(最后一个元素是确定的) for (int i = 0; i < sourceArray.length - 1; i++) { //-1 为了防止 j+1 下标越界,-i 每次变量都可以确认末尾元不需要参与下次遍历 for (int j = 0; j < sourceArray.length - i - 1; j++) { //当前元素和后一个比较,如果大于后一个元素进行交换 if (sourceArray[j] > sourceArray[j + 1]) { int temp = sourceArray[j]; sourceArray[j] = sourceArray[j + 1]; sourceArray[j + 1] = temp; } } System.out.println(i + ":" + Arrays.toString(sourceArray)); } return sourceArray; }

public static void main(String[] args) { int[] arr = new int[]{9, 8, 7, 6, 5, 4, 3, 2, 1}; System.out.println("sort:" + Arrays.toString(new BubbleSort().sort(arr))); } }

import java.util.Arrays; /** * @program:tpb * @description:选择排序 * 第一次从待排序的数据元素中选出最小(或最大)的一个元素,存放在序列的起始位置, * 然后再从剩余的未排序元素中寻找到最小(大)元素,然后放到已排序的序列的末尾。 * 以此类推,直到全部待排序的数据元素的个数为零。不稳定排序。 * @author:heshuangxi * @create:2020-06-30 19:49 **/ public class SelectionSort { public int[] sort(int[] sourceArray) { //遍历数组长度-1遍(最后一个元素是确定的) for (int i = 0; i < sourceArray.length - 1; i++) { //最小元素下标 int minIndex = i; //除去已知外每个元素比较,较小元素赋值到minIndex for (int j = i; j < sourceArray.length; j++) { if (sourceArray[j] < sourceArray[minIndex]) { minIndex = j; } } if (sourceArray[i] > sourceArray[minIndex]) { int temp = sourceArray[i]; sourceArray[i] = sourceArray[minIndex]; sourceArray[minIndex] = temp; System.out.println(i + ":" + Arrays.toString(sourceArray)); } } return sourceArray; }

public static void main(String[] args) { int[] arr = new int[]{9, 4, 7, 6, 5, 8, 3, 2, 1}; System.out.println("sort:" + Arrays.toString(new SelectionSort().sort(arr))); } }

经验分享 程序员 微信小程序 职场和发展