JAVA笔试又是快排!!!写在博客滥记于心!!!!!!!

来源:互联网 发布:安装完ubuntu无法启动 编辑:程序博客网 时间:2024/04/30 06:56

面试一家搞医疗软件的公司,笔试题又来一道排速排序,说是简单,现在可能也只是大学本科的无经验写的快排,先blog一下,以后应该会有优化.........

public void quickSort(int[] array){ //快排是不稳定的,如:  5、6.、6。、4 、1、2、3   ----选4做轴-----》 3、2、1、4、6。、6.、5  //明显两个6的位置换了

    if(array==null || array.length<2)

        return;

    _quickSort(array,0,array.length-1);

}

private void _quickSort(int[] array,int low,int high){

    if(low>=high)    return ;

    int tmpLow = low , tmpHigh = high , tmpNum = array[(high+low)/2];

    while(tmpLow<tmpHigh){  //while 1

        while(array[tmpLow]<tmpNum&&tmpLow<tmpHigh)

            tmpLow++;

         while(array[tmpHigh]>tmpNum&&tmpLow<tmpHigh)

            tmpHigh--;

        if(tmpLow<tmpHigh){ //用位与,相对加减,不会有溢出问题

               array[tmpLow] = array[tmpLow]^array[tmpHigh];

               array[tmpHigh] = array[tmpLow]^array[tmpHigh];

               array[tmpLow] = array[tmpLow]^array[tmpHigh];

        }

       tmpLow++;

       tmpHigh--;

    }//while 1 走完一趟快排

   _quickSort(array , low,(high+low)/2-1);//注意这两个段必然是全部的

   _quickSort(array, (high+low)/2, high);//不能把这里的(high+low)/2改为(high+low)/2+1,除非上面是(high+low)/2,否则这样会漏掉中间那个,而中间那个也不一定就是在这个位置

}

原创粉丝点击