如何从特定位置开始对数组进行排序

时间:2012-02-20 16:17:08

标签: java

我有一个数组:

int[] array = {1,2,3,4,5,6,7,8,9,10};

我想选择排序的起点。如果我选择6,则输出应为

(6,7,8,9,10,1,2,3,4,5)

2 个答案:

答案 0 :(得分:5)

我会分两个阶段:

  1. 为索引1(通常)
  2. 排序
  3. 将其旋转到所需的索引

答案 1 :(得分:0)

如果您尝试根据代码中指定的数组索引位置进行排序,则可以使用以下代码。

import java.util.Arrays;

公共类IndexBasedSort {

public static int[] getFirstIndexedArray(int[] originalArray, int arrayIndex) {
    int[] firstIndexedArray = new int[arrayIndex];
    for(int i=0;i<arrayIndex;i++){
        firstIndexedArray[i] = originalArray[i];
    }
    return firstIndexedArray;
}

public static int[] getNextIndexedArray(int[] originalArray, int arrayIndex) {
    int[] nextIndexedArray = new int[(originalArray.length - arrayIndex)];
    for(int i=0;i<nextIndexedArray.length;i++) {
        nextIndexedArray[i] = originalArray[i+arrayIndex];
    }
    return nextIndexedArray;
}

public static int[] sortArrayElements(int[] arrayElements) {
    Arrays.sort(arrayElements);
    return arrayElements;
}

public static int[] joinArrayElements(int[] firstArray, int[] nextArray) {
    int[] joinedArray = new int[(firstArray.length + nextArray.length)];
    for(int i=0;i<firstArray.length;i++) {
        joinedArray[i] = firstArray[i];
    }
    for(int i=0;i<nextArray.length;i++) {
        joinedArray[i+firstArray.length] = nextArray[i];
    }
    return joinedArray;
}

public static void printArrayElements(int[] arrayElements) {
    System.out.print("Sorted Array: ");
    for(int i=0;i<arrayElements.length;i++) {
        System.out.print(arrayElements[i]+", ");
    }
}

public static void run(int[] originalArray, int arrayIndex){
    printArrayElements(joinArrayElements(sortArrayElements(getFirstIndexedArray
            (originalArray, arrayIndex)), sortArrayElements(getNextIndexedArray(
                    originalArray, arrayIndex))));
}

public static void main(String[] args) {
    int[] originalArray = {10,9,8,7,6,5,4,3,2,1};
    int arrayIndex = 6;
    run(originalArray, arrayIndex-1);
}

}