简体   繁体   English

从右到左读取数组

[英]reading an array from right to left

ok, so I am suppose to get the algorithm of the selection sort, but modify it were it read from right to left and places the largest number at the end of the array. 好的,所以我想得到选择排序的算法,但是如果它是从右向左读取的,则对其进行修改并将最大的数字放在数组的末尾。 For example the array {3, 5, 2, 1, 4} will be { 5, 4, 3, 2, 1}. 例如,数组{3,5,2,1,4}将是{5,4,3,2,1}。 You may say just use the regular sort and then reverse the result, but that is not the way I am looking for. 您可能会说只使用常规排序,然后反转结果,但这不是我想要的方式。 So I attempted this and came up with this result. 所以我尝试了这个,并得出了这个结果。

reverseSelectionSort( A[0...n-1])
{
    for(int i=n-1; i=>1; i--)
    {
        int min = i;
        for(int j=i-1; j=>0; j--)
        {
            if(A[j] < A[min])
            {
                min = j;
            }
        }
        swap(A[i], A[min])
    }
}

Ok, that is what I came up with. 好的,这就是我想出的。 Did I do the algorithm correctly? 我算法正确吗?

Here is an implementation of selection sort in Java (decreading final order). 这是Java中选择排序的一种实现(对最终顺序进行解码)。

static void selectionSort(int[] a) {
   for (int i=0; i<a.length-1; i++) {
      int max=i;
      for (int j=i+1; j<a.length; j++) {
          if (a[j]>a[max]) {
             max=j;
          }
      }
      swap(a[i], a[max]);
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM