lichjx 2016-10-09 08:40 采纳率: 0%
浏览 756

快速排序中的一个疑问希望感兴趣的帮忙

问题描述:
两种选取key位置的方法完全相同,但是调用一个是函数内调用,另一种是函数外调用,但结果是一个起作用一个不起作用,请问这是为什么?下面上代码。

不起作用的调用函数:
///
/// 快速排序
///
/// 支持IComparable并实现CompareTo方法的类型数组
/// 分组的左边界(初始为数组内任意元素)
/// 分组的右边界(初始为数组右边界)
/// 计时器(默认null,如果从外部传入则需要设置startTime)
/// 是否是递归初始趟
///
public static string[] quickSort(T[] array, int low, int high, bool start, GCTiming tiObj = null)
{
if (tiObj == null)
{
tiObj = new GCTiming();
tiObj.StartTime();
}

        int pivot = low;
        if (low < high)
        {  
            while (low < high)
            {
                while (pivot < high)
                {
                    if (array[pivot].CompareTo(array[high]) <= 0)
                    {
                        high--;
                    }
                    else
                    {
                        array_swap(array, pivot, high);
                        pivot = high;
                        break;
                    }
                }

                while (low < pivot)
                {
                    if (array[low].CompareTo(array[pivot]) <= 0)
                    {
                        low++;
                    }
                    else
                    {
                        array_swap(array, low, pivot);
                        pivot = low;
                        break;
                    }
                }
            }
            //pivot = array_qsort_partition(array, low, high);

            quickSort(array, low, pivot - 1, false, tiObj);
            quickSort(array, pivot + 1, high, false, tiObj);
        }
        if (start)
        {
            //Thread.Sleep(1000);
            int a = 10;
            object b;
            //for (int i = 0; i < 100000; i++)
            //{
            //    b = (object)a;
            //}
            tiObj.StopTime();
            return new string[] { tiObj.Result().TotalMilliseconds.ToString(), SortUtil<T>.intArrToString(array) };
        }

        return null;
    }
  • 写回答

2条回答 默认 最新

  • lichjx 2016-10-09 08:41
    关注

    另一个起作用的调用方式:
    static void array_swap(T[] array, int i, int j)
    {
    T temp = array[i];
    array[i] = array[j];
    array[j] = temp;
    }

        /** 
         * @author  TIAN 
         * @brief   快速排序(哨兵筛选部分) 
         */
        static int array_qsort_partition(T[] array, int low, int hight)
        {
            int pivot = low;
    
            while (low < hight)
            {
                while (pivot < hight)
                {
                    if (array[pivot].CompareTo(array[hight]) <= 0)
                    {
                        hight--;
                    }
                    else
                    {
                        array_swap(array, pivot, hight);
                        pivot = hight;
                        break;
                    }
                }
    
                while (low < pivot)
                {
                    if (array[low].CompareTo(array[pivot]) <= 0)
                    {
                        low++;
                    }
                    else
                    {
                        array_swap(array, low, pivot);
                        pivot = low;
                        break;
                    }
                }
            }
    
            return pivot;
        }
    
        /** 
         * @author  TIAN 
         * @brief   快速排序(递归部分) 
         */
       public static string[] array_qsort(T[] array, int low, int high, bool start, GCTiming tiObj = null)
        {
            if (tiObj == null)
            {
                tiObj = new GCTiming();
                tiObj.StartTime();
            }
            if (low < high)
            {
                int pivot = array_qsort_partition(array, low, high);
                array_qsort(array, low, pivot - 1, false, tiObj);
                array_qsort(array, pivot + 1, high, false, tiObj);
            }
    
            if (start)
            {
                //Thread.Sleep(1000);
                int a = 10;
                object b;
                //for (int i = 0; i < 100000; i++)
                //{
                //    b = (object)a;
                //}
                tiObj.StopTime();
                return new string[] { tiObj.Result().TotalMilliseconds.ToString(), SortUtil<T>.intArrToString(array) };
            }
    
            return null;
        }
    

    这两种调用为什么一个起作用另一个不起作用呢?
    将主函数中的调用也一并奉上,方便大家复现和调试:
    main():
    class Program
    {
    static void Main(string[] args)
    {
    int orderSize = 20000;
    string[] lastBaseCounting = null;
    int[] arrFixedSize = getBefroeSortArr();
    int[] arrOrderSize = getBefroeSortArr2(orderSize);
    Console.WriteLine("Any key to start sort conting...\r\nPress ESC to exit this Program\r\n");
    while (Console.ReadKey().Key != ConsoleKey.Escape)
    {
    printStartInfo("fixedSizeArr", arrFixedSize);
    printStartInfo("orderSize", arrOrderSize);
    //选择排序
    string[] res = SortComponent.selectionSortSimple(getTmpArray(arrOrderSize));
    printEndInfo("selectionSortSimple:", fixContingTime(lastBaseCounting, res));
    //插入排序
    /*//这行会出问题,第一组选择排序的执行时间变成了0
    //res = SortComponent.insertSortSimple(getBefroeSortArr2(50000)); /
    /
    这样取结果就没问题,选择排序的执行时间会打印出来*/
    string[] res1 = SortComponent.insertSortSimple(getTmpArray(arrOrderSize));
    printEndInfo("insertSortSimple:", fixContingTime(res,res1));
    //冒泡排序
    string[] res2 = SortComponent.popSort(getTmpArray(arrOrderSize));
    printEndInfo("popSort:", fixContingTime(res1, res2));
    //鸡尾酒排序(双向冒泡排序)
    string[] res3 = SortComponent.cocktailSort(getTmpArray(arrOrderSize));
    printEndInfo("cocktailSort", fixContingTime(res2, res3));

                string[] res4 = SortComponent<int>.shellSort(getTmpArray(arrOrderSize));
                printEndInfo("shellSort", fixContingTime(res3, res4));
    
                string[] res5 = SortComponent<int>.quickSort(getTmpArray(arrOrderSize), 0, orderSize - 1, true);
                printEndInfo("quickSort", fixContingTime(res4, res5));
    
                //string[] res5 = SortComponent<int>.array_qsort(getTmpArray(arrOrderSize), 0, orderSize - 1, true);
                //printEndInfo("quickSort", fixContingTime(res4, res5));
    
                printEndInfoWithNoArrayRes("selectionSortSimple:", fixContingTime(lastBaseCounting, res));
                printEndInfoWithNoArrayRes("insertSortSimple:", fixContingTime(res, res1));
                printEndInfoWithNoArrayRes("popSort:", fixContingTime(res1, res2));
                printEndInfoWithNoArrayRes("cocktailSort:", fixContingTime(res2, res3));
                printEndInfoWithNoArrayRes("shellSort:", fixContingTime(res3, res4));
                printEndInfoWithNoArrayRes("quickSort:", fixContingTime(res4, res5));
    
                lastBaseCounting = res;
                arrOrderSize = getBefroeSortArr2(orderSize);
            }
            //Console.WriteLine("Sort program is end\r\nPress any key to exit program...");
            //Console.ReadKey();
        }
    
        static void PrintArray(string[] array)
        {
            Console.WriteLine(SortUtil<string>.intArrToString(array));
        }
    
        static void printStartInfo(string arrname, int[] array)
        {
            Console.WriteLine("{0} before sort is:\r\n", arrname);
            PrintArray(Array.ConvertAll<int, string>(array, s => s.ToString()));
        }
    
        static void printEndInfo(string name, string[] sortRes)
        {
            Console.WriteLine("after {0} sort:\r\n{2}\r\ntotal time is :{1}ms\r\n\r\n", name, sortRes[0], sortRes[1]);
        }
    
        static void printEndInfoWithNoArrayRes(string name, string[] sortRes)
        {
            Console.WriteLine("{0}\r\ntotal time is :{1}ms\r\n\r\n", name, sortRes[0], sortRes[1]);
        }
    
        static int[] getBefroeSortArr()
        {
            return new int[] { 2, 9, 2, 1, 8, 2, 3, 5, 19, 29, 13, 11, 45 };
            //return new int[] { 1, 18, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
        }
    
        static int[] getBefroeSortArr2(int length = 100)
        {
            int[] arr = new int[length];
            Random rn = new Random();
            for (int i = 0; i < length; i++)
            {
                arr[i] = rn.Next(1, length);
            }
            return arr;
        }
        /// <summary>
        /// 创建基础排序数列的副本
        /// </summary>
        /// <param name="arr">样本数列</param>
        /// <returns></returns>
        static int[] getTmpArray(int[] arr)
        {
            int[] tmpArr = new int[arr.Length];
            arr.CopyTo(tmpArr, 0);
            return tmpArr;
        }
    
        static string[] fixContingTime(string[] resPre,string[] resCur)
        {
            if (resPre == null)
            {
                return resCur;
            }
            string[] tempResForReturn = new string[2];
            resCur.CopyTo(tempResForReturn,0);
            double tmpContingTiem = double.Parse(resPre[0]);
            tempResForReturn[0] = (double.Parse(resCur[0]) - tmpContingTiem).ToString();
            return tempResForReturn;
        }
    }
    

    lichjx ()  发表于:2016-09-24 12:08:39  1 楼

    这个是交换方法的那个类
    class SortUtil
    {
    public static void swap(T[] array, int i, int min)
    {
    T temp = array[i];
    array[i] = array[min];
    array[min] = temp;
    }

        void swap7(int x, int y)
        {
            if (x == y)
                return;
            y = x + y - (x = y);
        }
    
        public static string intArrToString(T[] array)
        {
           return string.Join(",", Array.ConvertAll<T, string>(array, s => s.ToString()));
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集