Java数组排序:获取数组索引排序列表的快速方法

Java数组排序:获取数组索引排序列表的快速方法,第1张

Java数组排序:获取数组索引排序列表的快速方法

我将定制快速排序算法以同时在多个数组上执行交换 *** 作:索引数组和值数组。例如(基于此quicksort):

public static void quicksort(float[] main, int[] index) {    quicksort(main, index, 0, index.length - 1);}// quicksort a[left] to a[right]public static void quicksort(float[] a, int[] index, int left, int right) {    if (right <= left) return;    int i = partition(a, index, left, right);    quicksort(a, index, left, i-1);    quicksort(a, index, i+1, right);}// partition a[left] to a[right], assumes left < rightprivate static int partition(float[] a, int[] index, int left, int right) {    int i = left - 1;    int j = right;    while (true) {        while (less(a[++i], a[right]))      // find item on left to swap ;         // a[right] acts as sentinel        while (less(a[right], a[--j]))      // find item on right to swap if (j == left) break;// don't go out-of-bounds        if (i >= j) break;       // check if pointers cross        exch(a, index, i, j);    // swap two elements into place    }    exch(a, index, i, right);    // swap with partition element    return i;}// is x < y ?private static boolean less(float x, float y) {    return (x < y);}// exchange a[i] and a[j]private static void exch(float[] a, int[] index, int i, int j) {    float swap = a[i];    a[i] = a[j];    a[j] = swap;    int b = index[i];    index[i] = index[j];    index[j] = b;}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5104225.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-17
下一篇 2022-11-17

发表评论

登录后才能评论

评论列表(0条)

保存