Repository navigation
Expand file tree
/
Copy pathSort.java
More file actions
146 lines (118 loc) · 3.06 KB
/
Copy pathSort.java
File metadata and controls
146 lines (118 loc) · 3.06 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
package com.duweri.interview;
import javax.management.Descriptor;
public class Sort {
public static void main(String[] args) {
int[] testArr = {12,27,19,39,16,49,61,40,20,94,63,13,27,31,38,43,11,44,81,29,33,88,60,80,51,4,0,1,22,9,8};
// Sort.insertSort(testArr);
// Sort.bubbleSort(testArr);
// Sort.quickSort(testArr, 0, testArr.length-1);
Sort.selectSort(testArr);
Sort.display(testArr);
}
public static void display(int[] arr){
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]+",");
}
}
/**
* 插入排序
* 关键:1、临时变量保存待排序的数字
* 2、边比较边后移
* 适用情况:序列基本有序的时候
*/
public static void insertSort(int[] arr){
for (int i = 1; i < arr.length; i++) {
int temp = arr[i];//临时保存待插入序列
int j;//下面先保证J大于0再去访问arr[j]!!!!
for (j = i-1;j >= 0 && temp > arr[j] ; j--) {//带插入序列大于当前序列就前移--》从大到小排列
arr[j+1] = arr[j];
}
arr[j+1]=temp;
}
}
/**
* 希尔排序
*/
public static void shellSort(int[] arr){
for (int i = arr.length/2; i >= 1; i=i/2) {//子序列的划分
}
}
/**
* 冒泡排序
* 关键:1、外循环标识无序区和有序区
* 2、内循环每次将一个无序区的数字排到最前面
*/
public static void bubbleSort(int[] arr){
for (int i = 0; i <arr.length-1; i++) {//从后往前推小的
for (int j = arr.length-1; j>i; j--) {//从最后一个开始遍历
if (arr[j]>arr[j-1]) {
int temp = arr[j];//swap
arr[j] = arr[j-1];
arr[j-1] = temp;
}
}
}
}
/**
* 快速排序
* 关键: 1、选轴值
* 2、一次划分
* 3、递归快排
*/
public static void quickSort(int[] arr,int start,int end){
if(start<end){
int middle = partition(arr, start, end);
quickSort(arr, start, middle-1);
quickSort(arr, middle+1, end);
}
}
/**
* 以arr[0]为基准进行一次划分算法,左边都小于arr[0],右边都大于arr[0]
*/
private static int partition(int[] arr,int first,int end){
while(first < end){
//先扫描右端
while(first < end && arr[first]<arr[end]){
end--;
}
if(first < end){
int temp = arr[end];
arr[end] = arr[first];
arr[first] = temp;
first++;
}
//扫描左边
while(first < end && arr[first]<arr[end]){
first++;
}
if(first<end){
int temp = arr[end];
arr[end] = arr[first];
arr[first] = temp;
end--;
}
}
return first;
}
/**
* 选择排序:
* 每次遍历无序区选出最小的
* @param arr
*/
public static void selectSort(int[] arr){
int minIndex = 0;
for (int i = 0; i < arr.length-1; i++) {
minIndex = i;//指向最小的值的角标
for (int j = i+1; j < arr.length; j++) {//遍历无序区
if(arr[j] < arr[minIndex]){
minIndex = j;
}
}
if (minIndex != i) { //无序区遍历完了,找到最小的角标了,交换
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;//把temp放到有序区
}
}
}
}