if和while的区别
packageday13;importjava.util.Arrays;/***用java实现一个快速排序**/publicclassQuickSortDemo{publ...
package day13;
import java.util.Arrays;
/**
* 用java实现一个快速排序
*
*/
public class QuickSortDemo {
public static void main(String[] args) {
int[] ary = { 30, 10, 20, 30,50,80,30,40};
// quickSort(ary);
quickSort(ary, 0, ary.length-1);
System.out.println(Arrays.toString(ary));
// int id = partition(ary, 0, ary.length-1);
// System.out.println(Arrays.toString(ary)+"id:"+id);
}
public static void quickSort(int[] ary, int lower, int high) {
int pivot;
*************************************************************
10行 if(lower < high){
*********************************************
pivot = partition(ary, lower, high);
System.out.println(pivot);
quickSort(ary, lower, pivot - 1);
quickSort(ary, pivot+1, high);
}
}
// 找出中枢值、将比中枢值大的放在右边、比中枢值小的放在左边
// 50,30,80,50,30,20,10,80,60
public static int partition(int[] ary, int lower, int high) {
int pivot = ary[lower];
while (lower < high) {
while (lower < high && ary[high] >= pivot)
high--;
swap(ary, high, lower);
while (lower < high && ary[lower] <= pivot)
lower++;
swap(ary, high, lower);
}
return lower;
}
private static void swap(int[] ary, int high, int lower) {
int temp;
temp = ary[high];
ary[high] = ary[lower];
ary[lower] = temp;
}
}
这是我写的一个快速排序程序、上面的第10行、我开始使用的是while、但是怎么运行都是一个死循环、搞了半天、最后改成if就正确、我想这两个应该同样的道理呀!while在条件不成立时候也是跳出循环呀!为啥while就是死循环呢?求解?? 展开
import java.util.Arrays;
/**
* 用java实现一个快速排序
*
*/
public class QuickSortDemo {
public static void main(String[] args) {
int[] ary = { 30, 10, 20, 30,50,80,30,40};
// quickSort(ary);
quickSort(ary, 0, ary.length-1);
System.out.println(Arrays.toString(ary));
// int id = partition(ary, 0, ary.length-1);
// System.out.println(Arrays.toString(ary)+"id:"+id);
}
public static void quickSort(int[] ary, int lower, int high) {
int pivot;
*************************************************************
10行 if(lower < high){
*********************************************
pivot = partition(ary, lower, high);
System.out.println(pivot);
quickSort(ary, lower, pivot - 1);
quickSort(ary, pivot+1, high);
}
}
// 找出中枢值、将比中枢值大的放在右边、比中枢值小的放在左边
// 50,30,80,50,30,20,10,80,60
public static int partition(int[] ary, int lower, int high) {
int pivot = ary[lower];
while (lower < high) {
while (lower < high && ary[high] >= pivot)
high--;
swap(ary, high, lower);
while (lower < high && ary[lower] <= pivot)
lower++;
swap(ary, high, lower);
}
return lower;
}
private static void swap(int[] ary, int high, int lower) {
int temp;
temp = ary[high];
ary[high] = ary[lower];
ary[lower] = temp;
}
}
这是我写的一个快速排序程序、上面的第10行、我开始使用的是while、但是怎么运行都是一个死循环、搞了半天、最后改成if就正确、我想这两个应该同样的道理呀!while在条件不成立时候也是跳出循环呀!为啥while就是死循环呢?求解?? 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询