每学习一门语言,这三种排序算法是必须要会的,接下来就来学学Java中如何写着三种排序代码。
冒泡排序:
冒泡法排序 在一组数据序列中,从左端开始将相邻的两个数字进行比较,如果左边的数据比右边的大,则交换其位置, 一轮比较完成后,最大的数据会在数据序列最后的位置上“冒出”
public class Maopao {
public static void main(String[] args) {
int[] s = {5, 8, 3, 12, 24, 30, 18, 1, 10, 13};
//数组中有length属性 没有length方法
for (int i = 0; i < s.length - 1; i++) {//比较的轮数
for (int j = 0; j < s.length - 1 - i; j++) {
if (s[j] < s[j + 1]) {
int temp = s[j];
s[j] = s[j + 1];
s[j + 1] = temp;
}
}
}
for (int q:s) {
System.out.println(q);
}
}
}
选择排序:
选择法排序 在一组无序的数据序列中,将其最大的数据与最后一个数据进行位置交换,则最后一个数据就排好了位置。 再将剩下的为排列的数据中最大的数据与未排序的数据序列最后一个进行交换位置。
public class Xuanze {
public static void main(String[] args) {
int[] s = {5, 8, 3, 12, 24, 30, 18, 1, 10, 13};
for (int i = 0; i < s.length -1 ; i++) {
for (int j = i+1; j < s.length; j++) {
if (s[i] > s[j]){
int temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}
}
for (int i:s
) {
System.out.println(i);
}
}
}
插入排序:
像扑克牌一样,接上来的第一张是唯一的一张,也可认为是有序的,后面接上来的牌对前面有序的进行比较,插入到适当的位置 。
public class Charu {
public static void main(String[] args) {
int[] s = {5, 8, 3, 12, 24, 30, 18, 1, 10, 13};
for (int i = 1; i < s.length ; i++) {
int j = i -1;
int temp = s[i];
for (; j >= 0 ; j--) {
if (temp < s[j]){
s[j+1] = s[j];
}
else break;
}
s[j + 1] = temp;
}
for (int i:s
) {
System.out.println(i);
}
}
}