首页 > 技术文章 > 快速排序,冒泡排序算法

xiaohaizhuimeng 2017-10-12 11:23 原文

demo 如下:

package cn.szfesc.demo.client;

public class Test {

public static void main(String[] args) {

int[] numbers1 = { 49, 38, 65, 97, 76, 13, 27 };
int[] numbers2 = { 49, 38, 65, 97, 76, 13, 27 };

System.out.println("冒泡排序前:");
printArr(numbers1);
doubblsort(numbers1);
System.out.println("冒泡排序后:");
printArr(numbers1);
System.out.println("快速排序前:");
printArr(numbers2);
Arrysort(numbers2);
System.out.println("快速排序后:");
printArr(numbers2);

}

/**
* 冒泡排序
*
* @param numbers
*/
public static void doubblsort(int[] numbers) {
int tem = 0;
for (int i = 0; i < numbers.length; i++) {//遍历数据每个元素
for (int j = 0; j < numbers.length - 1; j++) {//将元素逐个对比
if (numbers[j] > numbers[j + 1]) {//比较交换
tem = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j + 1] = tem;
}
}
}
}

/**
* 快速排序:
* 把整个序列看做一个数组,把第零个位置看做中轴,和最后一个比,如果比它小交换,比它大不做任何处理;
* 交换了以后再和小的那端比,比它小不交换,比他大交换。这样循环往复,一趟排序完成,左边就是比中轴小的,
* 右边就是比中轴大的,然后再用分治法,分别对这两个独立的数组进行排序。
* @param numbers
*/
public static void Arrysort(int[] numbers) {
if (numbers.length > 0) {
quick(numbers, 0, numbers.length - 1);
}
}

/**
* 打印输出
*
* @param numbers
*/
public static void printArr(int[] numbers) {
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + ",");
}
}

/**
*
* @param numbers 带排序数组
* @param low 开始位置
* @param high 结束位置
*/
public static void quick(int[] numbers, int low, int high) {

if (low < high) {
int index = getMiddle(numbers, low, high);//将numbers数组进行一分为二
quick(numbers, low, index - 1);//对低字段表进行递归排序
quick(numbers, index + 1, high);//对高字段表进行递归排序
}
}

/**
* 查找出中轴(默认是最低位low)的在numbers数组排序后所在位置
* @param numbers带查找数组
* @param low开始位置
* @param high high 结束位置
* @return 中轴所在位置
*/
public static int getMiddle(int[] numbers, int low, int high) {

int key = numbers[low];
while (low < high) {
while (low < high && numbers[high] > key) {//从后半部分向前扫描
high--;
}
numbers[low] = numbers[high];//比中轴小的记录移到低端
while (low < high && numbers[low] < key) {//从前半部分向后扫描
low++;
}
numbers[high] = numbers[low];//比中轴大的记录移到高端
}

//前后下标已经重合,high 与 low都是一样
numbers[low] = key;
return low;
}
}

推荐阅读