开发者社区> 问答> 正文

java中快速排序有时成功有时失败

代码:

public class Sorting {
public static void main(String[] args) {
// TODO Auto-generated method stub
int len = 10;
int arr[] = new int [len];
for(int i=0;i<len;i++)
{
//Math.random()表示0~1之间的随机数
arr[i] = (int)(Math.random()*10000);
}
Quick_Sort qs = new Quick_Sort();
qs.sort(arr);
for(int i=0;i<arr.length;i++)
{
System.out.print(arr[i]+" ");
}
}
}
class Quick_Sort
{
public void sort(int arr[])
{
int f = 0;
int l = (arr.length-1);
this.digui(f, l, arr);
}
private void digui(int first,int last,int arr[])
{
int temp = arr[first];
int f = first;
int l = last;
while(f<l)
{
while(f<l&&temp<=arr[l])
{
l--;
}
arr[f] = arr[l];
while(f=arr[f])
{
f++;
}
arr[l] = arr[f];
}
arr[f] = temp;
if(first<last)
{
this.digui(first, f-1, arr);
this.digui(f+1,last, arr);
}
}
}

展开
收起
蛮大人123 2016-03-18 10:20:50 2190 0
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪

    程序运行了下,会数组越界.

     public static void quickSort(int[] arr,int low,int high){
            if(high > low){
                int part = partition(arr,low,high);
                //System.out.println("part="+part);
                quickSort(arr,low,part - 1);
                quickSort(arr,part+1,high);
            }
        }
        //找寻分界点
        public static int partition(int[] arr,int low , int high){
            int first = low;
            int pivot = arr[low];
            low++;
            while(high > low){
                //从左边找比pivot大的数
                while(low <= high && arr[low] <= pivot ){
                    low++;
                }
                //从右边找比pivot小或等于的数
                while(high >= low && arr[high] > pivot ){
                    high--;
                }
                //交换
                if(high > low){
                    int temp = arr[high];
                    arr[high] = arr[low];
                    arr[low] = temp;
                }
            }
            //此时high = low - 1;
            //且high之前的元素都小于等于pivot,low之后的元素都大于pivot
            //System.out.println("low="+low+";high="+high+":"+Arrays.toString(arr));
            if(high > first){
                int temp = arr[high];
                arr[high] = arr[first];
                arr[first] = temp;
                //System.out.println("part="+high+":"+Arrays.toString(arr));
                return high;
            }else{
                //System.out.println("part="+high+":"+Arrays.toString(arr));
                return first;
            }
        }
    2019-07-17 19:06:02
    赞同 展开评论 打赏
问答分类:
问答标签:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载