【问题标题】:Using quick sort algorithm to sort objects alongside respective integers使用快速排序算法将对象与相应的整数一起排序
【发布时间】:2020-05-29 20:37:59
【问题描述】:

我正在编写一个基于调查的程序,其中有一种方法可以将人们的兼容性与用户的兼容性进行比较。

我有一个快速排序算法,可以将整数从最大到最不有效地排序,但是我需要在整数数组(这是一个人的兼容性数组)旁边对一组人进行排序。如何对人员数组进行排序,以使其与各自的整数兼容性相匹配?

快速排序算法:

public static void qsort(People [] ppl, Integer [] a, Integer si, Integer ei){
        //base case
        if(ei<=si || si>=ei){}

        else{ 
            Integer pivot = a[si]; 
            Integer i = si+1; Integer tmp; 

            //partition array 
            for(Integer j = si+1; j<= ei; j++){
                if(pivot < a[j]){
                    tmp = a[j]; 
                    a[j] = a[i]; 
                    a[i] = tmp; 

                    i++; 
                }
            }

            //put pivot in right position
            a[si] = a[i-1]; 
            a[i-1] = pivot; 

            //call qsort on right and left sides of pivot
            qsort(a, si, i-2); 
            qsort(a, i, ei); 
        }
    }

【问题讨论】:

    标签: arrays sorting quicksort


    【解决方案1】:
    public static void qsort(People [] ppl, Integer [] a, Integer si, Integer ei){
        //base case
        if(ei<=si || si>=ei){}
        else{ 
            Integer pivot = a[si]; 
            People pPivot = ppl[si];
            Integer i = si+1; Integer tmp; People pTmp; 
    
            //partition array 
            for(Integer j = si+1; j<= ei; j++){
                if(pivot < a[j]){
                    tmp = a[j]; 
                    pTmp = ppl[j];
                    a[j] = a[i]; 
                    ppl[j]=ppl[i];
                    a[i] = tmp; 
                    ppl[i]=pTmp;
                    i++; 
                }
            }
    
            //put pivot in right position
            a[si] = a[i-1]; 
            ppl[si] = ppl[i-1];
            a[i-1] = pivot; 
            ppl[i-1]=pPivot;
    
            //call qsort on right and left sides of pivot
            qsort(ppl, a, si, i-2); 
            qsort(ppl, a, i, ei); 
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-18
      • 1970-01-01
      • 2021-06-15
      相关资源
      最近更新 更多