algo/java/11_sorts/Sorts.java
carlos ac6ad844c9 Merge remote-tracking branch 'upstream/master'
Merge remote-tracking branch 'upstream/master'
2018-10-23 17:51:36 +08:00

85 lines
1.8 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package sorts;
/**
* 冒泡排序、插入排序、选择排序
*
* Author: Zheng
*/
public class Sorts {
// 冒泡排序a是数组n表示数组大小
public static void bubbleSort(int[] a, int n) {
if (n <= 1) return;
for (int i = 0; i < n; ++i) {
// 提前退出标志位
boolean flag = false;
for (int j = 0; j < n - i - 1; ++j) {
if (a[j] > a[j+1]) { // 交换
int tmp = a[j];
a[j] = a[j+1];
a[j+1] = tmp;
// 此次冒泡有数据交换
flag = true;
}
}
if (!flag) break; // 没有数据交换,提前退出
}
}
// 插入排序a表示数组n表示数组大小
public static void insertionSort(int[] a, int n) {
if (n <= 1) return;
for (int i = 1; i < n; ++i) {
int value = a[i];
int j = i - 1;
// 查找要插入的位置并移动数据
for (; j >= 0; --j) {
if (a[j] > value) {
a[j+1] = a[j];
} else {
break;
}
}
a[j+1] = value;
}
}
// 选择排序a表示数组n表示数组大小
public static void selectionSort(int[] a, int n) {
if (n <= 1) return;
<<<<<<< HEAD
for (int i = 0; i < n; ++i) {
// 查找最小值
int minIndex = i;
int minValue = a[i];
for (int j = i; j < n; ++j) {
if (a[j] < minValue) {
minValue = a[j];
=======
for (int i = 0; i < n - 1; ++i) {
// 查找最小值
int minIndex = i;
for (int j = i + 1; j < n; ++j) {
if (a[j] < a[minIndex]) {
>>>>>>> upstream/master
minIndex = j;
}
}
<<<<<<< HEAD
=======
if (minIndex == i)
continue;
>>>>>>> upstream/master
// 交换
int tmp = a[i];
a[i] = a[minIndex];
a[minIndex] = tmp;
}
}
}