Skip to content

Commit 9869f97

Browse files
committed
data-struct-sort
1 parent 260a887 commit 9869f97

File tree

4 files changed

+113
-0
lines changed

4 files changed

+113
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package com.fantj.dataStruct.simplesort;
2+
3+
/**
4+
* 冒泡排序
5+
* Created by Fant.J.
6+
* 2017/12/20 19:43
7+
*/
8+
public class BubbleSort {
9+
//小值往前排
10+
public static void sort(long [] arr){
11+
long tmp = 0;
12+
for (int i = 0;i < arr.length;i++){
13+
for (int j = arr.length-1;j>i;j--){
14+
if (arr[j]<arr[j-1]){
15+
tmp = arr[j];
16+
arr[j] = arr[j-1];
17+
arr[j-1] = tmp;
18+
}
19+
}
20+
}
21+
}
22+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package com.fantj.dataStruct.simplesort;
2+
3+
/**
4+
* Created by Fant.J.
5+
* 2017/12/20 20:56
6+
*/
7+
public class InsertSort {
8+
public static void sort(long [] arr){
9+
int i, j;
10+
long target;
11+
//假定第一个元素被放到了正确的位置上
12+
//这样,仅需遍历1 - n-1
13+
for (i = 1; i < arr.length; i++)
14+
{
15+
j = i;
16+
target = arr[i];
17+
//如果当前值小于前面的值,就交换它们
18+
while (j > 0 && target < arr[j - 1])
19+
{
20+
arr[j] = arr[j - 1];
21+
j--;
22+
}
23+
arr[j] = target;
24+
}
25+
}
26+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package com.fantj.dataStruct.simplesort;
2+
3+
/**
4+
* 选择排序
5+
* Created by Fant.J.
6+
* 2017/12/20 19:56
7+
*/
8+
public class SelectionSort {
9+
public static void sort(long []arr){
10+
11+
int k = 0;
12+
long temp = 0;
13+
for (int i = 0;i<arr.length-1;i++){
14+
k = i;
15+
for (int j = i;j<arr.length;j++){
16+
if (arr[j] < arr[k]){
17+
//拿到最小值对应的index
18+
k = j;
19+
}
20+
}
21+
//将k(最小值)和i(当前值)交换
22+
temp = arr[i];
23+
arr[i] = arr[k];
24+
arr[k] = temp;
25+
}
26+
}
27+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package com.fantj.dataStruct.simplesort;
2+
3+
/**
4+
* Created by Fant.J.
5+
* 2017/12/20 19:50
6+
*/
7+
public class TestSort {
8+
public static void main(String[] args) {
9+
long []arr = new long[5];
10+
arr[0] = 19;
11+
arr[1] = 18;
12+
arr[2] = 20;
13+
arr[3] = 17;
14+
arr[4] = 21;
15+
// arr[0] = 19;
16+
// arr[1] = 18;
17+
// arr[2] = 17;
18+
// arr[3] = 16;
19+
// arr[4] = 15;
20+
21+
System.out.print("[");
22+
for (long num :arr){
23+
System.out.print(num + " ");
24+
}
25+
System.out.print("]");
26+
System.out.println();
27+
28+
// BubbleSort.sort(arr);
29+
// SelectionSort.sort(arr);
30+
InsertSort.sort(arr);
31+
System.out.print("[");
32+
for (long num :arr){
33+
System.out.print(num + " ");
34+
}
35+
System.out.print("]");
36+
37+
}
38+
}

0 commit comments

Comments
 (0)