• 给定数组,查找最小的k个元素或最大的k个元素


    本意是这样的,给定一个整数数组,查找最小k个元素或最大k个元素。

    假定有这样一组数列 { 10, 33, 2, 4, 55, 6, 12, 34, 456, 66, 43, 23, 65, 1, 345, 61, 76, 31, 43, 76 };

    如和求出最小的k个值,或最大的k个值?下面我结合快速排序来进行了查找,本人只是做了一个实例,抛砖引玉,希望大家有更好的方法,代码是用C#代码实现的。

     private int Partition(int[] R, int low, int high)
            {
                int temp = R[low];
                 while (low < high)
                {
                    while (low < high && temp <= R[high])
                    {
                        high--;
                    }
                    R[low] = R[high];
                    while (low < high && temp >= R[low])
                    {
                        low++;
                    }
                    R[high] = R[low];
                }
                R[low] = temp;
                return low;
            }

     /// <summary>
            /// 快速排序
            /// </summary>
            /// <param name="R"></param>
            /// <param name="low"></param>
            /// <param name="high"></param>
            private void QuickSort(int[] R, int low, int high,int k)
            {
              
                int pivotLoc = 0;
                if (low < high)
                {
                    pivotLoc = Partition(R, low, high);
                    QuickSort(R, low, pivotLoc - 1, k);
                    if ( pivotLoc <= k)
                    {                
                        QuickSort(R, pivotLoc + 1, high, k);
                    }                                      
                }
            }

      这是求k个最小值的,如果求k个最大值的,只需要修改下partition方法就可以了,本质上是一致的。

     /// <summary>
            /// 从大到小排序
            /// </summary>
            /// <param name="R"></param>
            /// <param name="low"></param>
            /// <param name="high"></param>
            /// <returns></returns>
            private static int Big_To_Small_Partition(int[] R, int low, int high)
            {
                int temp = R[high];
                while (low < high)
                {
                    while (low < high && temp <= R[low])
                    {
                        low++;
                    }
                    R[high] = R[low];
                    while (low < high && temp > R[high])
                    {
                        high--;
                    }
                    R[low] = R[high];
                }
                R[high] = temp;
                return high;
            }

  • 相关阅读:
    mysql 8 查询报错(sql_mode=only_full_group_by)
    docker安装mysql8版本后 客户端连接出现client does not support authentication...
    docker常用命令
    查看tomcat日志相关Linux命令
    java项目部署到linux服务器涉及的命令
    ehcache与redis对比
    JS中调用BigDecimal处理金额
    thymeleaf模板 th:href 踩坑
    汇总一些绝对有价值的解决方案,边学习边收集
    spring注解总结,spring注解大全
  • 原文地址:https://www.cnblogs.com/shaosks/p/2274721.html
Copyright © 2020-2023  润新知