/**
* 创建时间:2019年3月7日 下午5:35:32
* @author 张十一先生
* 类说明:
*/
public class QuickSort {
public static void quickSort(int[] arr, int start, int end) {
// 这个参照元素可以是任意元素,不过一般以第一个为准
int temp = arr[start];
int low = start;
int high = end;
// 这是外层循环,只要low指针没和high指针重合就找下去
while (low < high) {
// 先从后往前找,若查找的元素都比参照元素要大,则让指针往前移动就可以了
while (low < high && arr[high] >= temp) {
high--;
}
// 若从后往前搜索的过程中发现有元素比参照元素小,则把这个元素与覆盖到low指针所在位置
arr[low] = arr[high];
// 同上
while (low < high && arr[low] <= temp) {
low++;
}
arr[high] = arr[low];
}
// 这时候low和high指针重合,把参照元素放到它应该待的位置
arr[low] = temp;
// 这里开始进行迭代,让左半部和右半部中的元素也找到自己合适的位置
if (low > start) {
quickSort(arr, start, low - 1);
}
if (high < end) {
quickSort(arr, low + 1, end);
}
}
public static void main(String[] args) {
int[] arr = new int[] { 7, 2, 4, 8, 6, 5, 9 };
quickSort(arr, 0, arr.length-1);
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}
-----------------------------------------------------------------------------------------------------------------------
/**
* 创建时间:2019年3月7日 下午6:00:25
*
* @author 张十一先生 类说明: 插入排序:将元素一个一个插入到已经排好序的队列中去
*/
public class InsertSort {
public static void main(String[] args) {
int[] arr = new int[] { 7, 2, 4, 8, 6, 5, 9 };
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + "|");
}
insertSort11(arr);
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
public static void insertSort11(int[] arr) {
// 插入排序中默认第一个元素就是排好的
for (int i = 1; i < arr.length; i++) {
// 找到目标元素的前一个元素
int frontIndex = i - 1;
// 将目标元素赋值给临时变量
int temp = arr[i];
// 若发现前面的元素比临时变量要大,就向后统一移位
while (frontIndex > 0 && arr[frontIndex] >= temp) {
arr[frontIndex + 1] = arr[frontIndex];
frontIndex--;
}
// while循环结束说明此时frontIndex所在位置的前一个元素已经比目标元素小了,这是后把目标元素放到正确的位置
arr[frontIndex + 1] = temp;
}
}
}
-----------------------------------------------------------------------------------------------------------------------
/**
* 创建时间:2019年3月7日 下午8:00:34
* @author 张十一先生
* 类说明:
*/
public class ChoseInsert {
public static void main(String[] args) {
int[] arr = new int[] { 7, 2, 4, 8, 6, 5, 9 };
chose(arr);
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
public static void chose(int[] arr) {
// 找到最小的元素去替换无序数组的第一个元素,因为最后一个剩下的肯定就是最大的所以只需要leng-1次就够了
for (int i = 0; i < arr.length - 1; i++) {
// 这个k相当于一个临时index,最后把最小元素的下标赋给它
int k = i;
// 从无序数组中找到最小的元素所在的位置,并调换无序数组中的第一个元素和这个最小元素
for (int j = i + 1; j < arr.length; j++) {
if (arr[k] > arr[j]) {
k = j;
}
}
if (i != k) {
int temp = arr[i];
arr[i] = arr[k];
arr[k] = temp;
}
}
}
}