您的位置:首页 > 其它

冒泡排序,快速排序

2016-03-09 11:16 260 查看
public class TestSort {

public static void main(String[] args) {
int nums[] = { 7, 5, 3, 8, 4, 6, 1, 2 };
// bubbleSort(nums);
quickSort(nums, 0, nums.length - 1);
printNums(nums);
}

/**
* 冒泡排序
*/
public static void bubbleSort(int[] nums) {
int temp;
for (int i = 0; i < nums.length - 1; i++) {
for (int j = 0; j < nums.length - 1 - i; j++) {
if (nums[j] > nums[j + 1]) {
temp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = temp;
}
}
}
}

/**
* 快速排序
*/
public static void quickSort(int[] nums, int left, int right) {
if (left >= right) {
return;
}
int i = left, j = right, x = nums[left];
while (i < j) {
while (i < j) {
if (nums[j] < x) {
nums[i] = nums[j];
break;
}
j--;
}
if (i < j) {
i++;
}
while (i < j) {
if (nums[i] > x) {
nums[j] = nums[i];
break;
}
i++;
}
if (i < j) {
j--;
}
}
nums[i] = x;
quickSort(nums, left, i - 1);
quickSort(nums, i + 1, right);
}

public static void printNums(int[] nums) {
StringBuilder sb = new StringBuilder();
for (int num : nums) {
sb.append(num + ", ");
}
System.out.println(sb.toString());
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐