黑马程序员--java中的几个简单排序

来源:互联网 发布:tensorflowgpu windows 编辑:程序博客网 时间:2024/05/21 12:41
------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------

java中的几个简单排序

package cn.test;


public class Bubble {
public static void main(String[] args) {
int[] a = { 1, 4, 2, 5, 6, 7 };
xuanZe(a);
System.out.println();
shell(a);
System.out.println();
chaRu(a);
System.out.println();
BubbleSortArray( a);
}
static void BubbleSortArray(int[] a) {
for (int i = 1; i < a.length; i++) {
for (int j = 0; j < a.length - i - 1; j++) {
if (a[j] > a[j + 1])// 比较交换相邻元素
{
int temp;
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
for (int i : a) { System.out.print(i+" "); }
}


static void xuanZe(int[] x) {
for (int i = 0; i < x.length; i++) {
int lowerIndex = i;
// 找出最小的一个索引
for (int j = i + 1; j < x.length; j++) {
if (x[j] < x[lowerIndex]) {
lowerIndex = j;
}
}
// 交换
int temp = x[i];
x[i] = x[lowerIndex];
x[lowerIndex] = temp;
}
for (int i : x) {
System.out.print(i + " ");
}
}
// 插入排序
public static void chaRu(int[] x) {
for (int i = 1; i < x.length; i++) {
// i从一开始,因为第一个数已经是排好序的啦
for (int j = i; j > 0; j--) {
if (x[j] < x[j - 1]) {
int temp = x[j];
x[j] = x[j - 1];
x[j - 1] = temp;
}
}
}
for (int i : x) {
System.out.print(i + " ");
}
}

// 希尔排序

希尔排序是一种高级排序,它是由插入排序进化来的,插入排序是将未排的数据依次与前面已排好的数据进行比较移动,这样如果一个较小的数排在靠后的位置,那么要找到这个数的正确位置就要进行较多次移动。希尔排序改进了这种方式,它将每次比较的间隔扩大,排过一次之后数据就分阶段有序了,之后逐渐缩小这个间隔再进行排序。这样做的目的就是让数据一开始可以在一个较大的范围内进行移动,待基本有序后数据的移动量就小了很多

public static void shell(int[] x) {
// 分组
for (int increment = x.length / 2; increment > 0; increment /= 2) {
// 每个组内排序
for (int i = increment; i < x.length; i++) {
int temp = x[i];
int j = 0;
for (j = i; j >= increment; j -= increment) {
if (temp < x[j - increment]) {
x[j] = x[j - increment];
} else {
break;
}
}
x[j] = temp;
}
}
for (int i : x) {
System.out.print(i + " ");
}
}
}
0 0
原创粉丝点击