简体   繁体   中英

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}. 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).

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]);
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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