- 概念:将一组无序的数列,排序成有序数列,升序列和降序列。
升序:后面的值一定比前面任意一个值要大。
1,7,9,10,11,12,19,20,21
降序:后面的值一定比前面任意一个值要小。
20,19,8,7,5,1.0,-1
一、冒泡排序
1.1 概念
概念:将相邻的两个元素进行比较,以升序列为例,如果前面的值比后面的值大了,则两者交换,否则不交换。
比如:7,9,6,10,11,5,4
排序为升序列:4,5,6,7,9,10,11
1.2 冒泡排序图解
1.3 实现代码
public class BubbleSort {
public static void main(String[] args) {
int[] num = {7,9,6,10,11,5,4};
System.out.print("排序前:");
for(int i = 0;i < num.length;i++) {
System.out.print(num[i]+",");
}
//排序:
for(int i = 0;i < num.length;i++) {
for(int j = 0;j < num.length-1-i;j++) {
if(num[j] > num[j+1]) {
int temp = num[j];
num[j] = num[j+1];
num[j+1] = temp;
}
}
}
System.out.println();
System.out.print("排序后:");
for(int i = 0;i < num.length;i++) {
System.out.print(num[i]+",");
}
}
}
二、选择排序
2.1 概念
依次取到数组的每一个下标,用该下标的后面所有元素与该下标的元素进行比较,如果是升序列,该下标元素值比后面元素值大了,则两者交换。否则不交换。
2.2 选择排序图解
2.3 实现代码
public class SelectSort {
public static void main(String[] args) {
int[] num = {1,11,9,8,3,2,7};
System.out.print("排序前:");
for(int i = 0;i < num.length;i++) {
System.out.print(num[i]+",");
}
//排序:
for(int i = 0, len = num.length-1;i < len;i++) {
for(int j = i+1;j < num.length;j++) {
if(num[i] > num[j]) {
int temp = num[i];
num[i] = num[j];
num[j] = temp;
}
}
}
System.out.println();
System.out.print("排序后:");
for(int i = 0;i < num.length;i++) {
System.out.print(num[i]+",");
}
}
}
三、插入排序
3.1 概念
1)把所有的元素分为两组,已排序和未排序的。
2)找到未排序的组中的第一个元素,向已经排序的数组中进行插入。
3)倒叙遍历已经排序的元素,一次和待插入的元素进行比较,知道找到一个元素小于等于待插入元素,那么就把待插入元素放到这个位置。
3.2 插入排序图解
图示说明:首先将第一个元素定义为已排序的组,其余的元素为未排序的组,接下来每次取未排序组里面的第一个元素,从已排序组里面倒着遍历,将遍历到的元素和选出未排序的第一个元素进行比较,如果前者比后者元素值大,则两者交换,直到该元素在已排序元素中遇到比它还小或者等于的元素,结束。
3.3 实现代码
/**
*
* <p>Title: InsertSort</p>
* <p>Description: 插入排序</p>
* @author Alon
* @date 2020年8月2日 下午4:07:58
* @version 1.0
*/
public class InsertSort {
public static void main(String[] args) {
//排序:
sort();
}
/**
*
*<p>Title: sort</p>
*<p>Description: 插入排序</p>
*/
public static void sort() {
//定义一个数组
int[] num = {4,3,2,10,12,1,5,6};
//排序前:
System.out.print("排序前:");
for(int i = 0;i < num.length;i++) {
System.out.print(num[i]+",");
}
//排序:外层排序表示取到从1及以后的每一个下标索引,i处值实际为未排序的第一个元素
for(int i = 1;i < num.length;i++) {
//内层循环是倒着遍历已排序的组
for(int j = i;j > 0;j--) {
//比较,用未排序中的第一个元素和已排序中的每一个元素比较
if(num[j-1] > num[j]) {
//交换
int temp = num[j-1];
num[j-1] = num[j];
num[j] = temp;
}else {
//否则说明找到了比自己小于或者等于的元素了,停止内层循环
break;
}
}
}
System.out.println();
System.out.print("排序后:");
for(int i = 0;i < num.length;i++) {
System.out.print(num[i]+",");
}
}
}
联系邮箱:alon_note@163.com
公众号:菜鸟崛起