# 排序

package cn.edu.hdu.chenpi.plib;

import java.util.Arrays;

public class App {

public static void main(String[] args) {
Integer[] arr = { 49, 38, 65, 97, 76, 13, 27, 49 };

for (int i = 0; i < arr.length - 1; i++) {
//用于提前结束判断
boolean changeFlag = false;
for (int j = 0; j < arr.length - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
changeFlag = true;
}
}
if (changeFlag == false)
break;
System.out.println("第" + (i + 1) + "次:" + Arrays.asList(arr));
}
System.out.println(Arrays.asList(arr));
;
}
}

package cn.edu.hdu.chenpi.plib;

public class App {

public static void main(String[] args) {
int[] arr = { 49, 38, 65, 97, 76, 13, 27, 49 };
App.quickSort(arr, 0, arr.length - 1);
for (int t : arr) {
System.out.println(t);
}
}

public static int trip(int[] arr, int begin, int end) {
int c = arr[begin];
int i = begin, j = end;
//最后一个空位
int index = 0;
while (i < j) {
//从后往前找
while (i < j && arr[j] >= c) {
j--;
}
arr[i] = arr[j];
index = j;
i++;

if (i >= j) break;

//从前往后找
while (i < j && arr[i] <= c) {
i++;
}
arr[j] = arr[i];
index = i;
j--;

}

arr[index] = c;

//打印一趟排序后的结果
for (int t : arr) {
System.out.print(t + " ");
}
System.out.println(index);
return index;
}

public static void quickSort(int[] arr, int begin, int end) {
if (begin < end) {
int middle = App.trip(arr, begin, end);

App.quickSort(arr, begin, middle - 1);
App.quickSort(arr, middle + 1, end);
}
}
}

n个元素的序列{k1，k2，…,kn}当且仅当满足下列关系之一时，称之为堆。

情形1：ki <= k2i 且ki <= k2i+1 最小化堆小顶堆

情形2：ki >= k2i 且ki >= k2i+1化堆大顶堆

posted @ 2019-03-08 23:33  风一样的码农  阅读(831)  评论(0编辑  收藏