您的位置:首页 > 职场人生

面试--排序(75)

2017-01-09 13:48 218 查看
public class BubbleQuickSort {
public void bubbleSort() {
int a[] = {49, 28, 65, 97, 76, 13, 27, 49, 78, 34, 12, 64, 5, 2, 62, 99, 56, 17, 18, 23, 34, 15, 23, 53, 51};
int temp = 0;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a.length - i - 1; j++) {
if (a[j] > a[j + 1]) {
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
for (int i = 0; i < a.length; i++) {
System.out.print(" " + a[i]);
}
}

public void quickSort() {
int a[] = {49, 28, 65, 97, 76, 13, 27, 49, 78, 34, 12, 64, 5, 2, 62, 99, 56, 17, 18, 23, 34, 15, 23, 53, 51};
quick(a);
for (int i = 0; i < a.length; i++) {
System.out.print(" " + a[i]);
}
}

private void quick(int[] a) {
if (a.length > 0) {
_quickSort(a, 0, a.length - 1);
}
}

private void _quickSort(int[] list, int low, int high) {
if (low < high) {
int middle = getMiddle(list, low, high);//将list一分为二
_quickSort(list, low, middle - 1);
_quickSort(list, middle + 1, high);
}
}

private int getMiddle(int[] list, int low, int high) {
int tmp = list[low];//数组的第一个作为中轴
while (low < high) {
while (low < high && list[high] >= tmp) {
high--;
}
list[low] = list[high];//比中轴小的记录移动到低端

while (low < high && list[low] <= tmp) {
low++;
}
list[high] = list[low];
}
list[high]  = tmp;
return high;
}

public static void main(String[] args) {
new BubbleQuickSort().bubbleSort();
System.out.println("\r\n");
new BubbleQuickSort().quickSort(); //非递归使用  栈数据结构
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  面试 sort
相关文章推荐