如果已排序,请查找数组的索引

时间:2014-09-07 16:55:52

标签: sorting

假设我有一个数组{4,2,9,6}。我想按升序排序这个数组。但反而 对于排序数组,我希望输出为索引 好像它已经分类了。例如,在这种情况下排序 数组将是{2,4,6,9}并且所需的输出将是 {1,0,3,2}。我尝试了以下,但不起作用。任何 建议好吗?

#include <iostream>
#include <time.h>
using namespace std;


void quickSort(int arr[], int index[], int left, int right) {
    int i = left, j = right;
    int tmp;
    int pivot = arr[(left + right) / 2];

    /* partition */
    while (i <= j) {
        while (arr[i] < pivot)
            i++;
        while (arr[j] > pivot)
            j--;
        if (i <= j) {
            tmp = arr[i];
            arr[i] = arr[j];
            index[j] = index[i];
            arr[j] = tmp;
            i++;
            j--;
        }
    };

    /* recursion */
    if (left < j)
        quickSort(arr,index, left, j);
    if (i < right)
        quickSort(arr,index, i, right);
}

int main() {
    srand(time(NULL));
    int const N = 5;
    int arr[N], index[N];
    for(int i = 0; i < N; i++){
        arr[i] = rand() % 100 + 1;
        index[i] = i;
    }
    for(int i = 0; i < N; i++)
        cout << arr[i] << " ";
    cout << endl;
    int left = 0; int right = N-1;
    quickSort(arr,index, left, right);
    for(int i = 0; i < N; i++)
        cout << arr[i] << " ";
    cout << endl;
    for(int i = 0; i < N; i++)
        cout << index[i] << " ";
    cout << endl;
    return(0);
}

1 个答案:

答案 0 :(得分:0)

我尝试了您的问题,并且能够通过插入排序来解决。这是我的代码(Java):

public static void insertionSortWithIndex(int[] a){
int x = 1;
// List<Integer> indexArray = new ArrayList<>();
int[] indexArray = new int[a.length];
int[] unsortedArray = new int[a.length];
for (int d = 0; d < a.length; d++) {
  unsortedArray[d] = a[d];
}

/* Your regular insertion sort algorithm */
while (x < a.length) {
  int c = x;
  while (c > 0 && a[c] < a[c-1]){
    swap(a, c, c-1);
    c--;
  }
  x++;


}
// System.out.println("Unsorted Array: " + Arrays.toString(unsortedArray));

 for (int unsorted = 0; unsorted < unsortedArray.length; unsorted++) {
    for (int sorted = 0; sorted < a.length; sorted++) {
      /* Main Index Ordering Logic: 
         if unsortedArray at unsorted index (unsortedArray[unsorted]) equals to sortedArray at sorted index, 
         then append unsorted index to will-be printed array */

        if (unsortedArray[unsorted] == a[sorted]) {
           indexArray[sorted] = unsorted; // append index of this number before sorting to indexArray at number's sorted position

      }

    }

  }

  System.out.println(Arrays.toString(indexArray));

}


/* Swap Method */
public static void swap(int[] a, int i, int j) {
  int temp = a[i];
  a[i] = a[j];
  a[j] = temp;


}

public static void main(String[] args) {
   int[] a {3, 4, 6, 5};

   insertionSortWithIndex(z);

   // output: {0, 1, 3, 2}

}

本质上,我所做的是在插入排序算法上添加了一些额外的逻辑,以便它可以基于排序后的数字数组返回正确的索引数组。

注意:此附加组件可能适用于每种排序算法;但是,我尚未对其进行测试。此外,此修改后的插入排序算法仅适用于没有重复元素的数组(截至2018年11月12日)。我将进行测试,实施这些改进并尽快更新问题。