我已经实现了一种排序算法来对无序整数数组进行排序。如果我投入一个100,000个元素的阵列,它需要大约10,500毫秒才能返回。我的算法是快还是慢?以下是代码。
public static void sort(int[] array) {
int lastItem = array[array.length - 1];
int length = array.length;
for (int j = 0; j < array.length; j++) {
for (int i = 0; i < length; i++) {
if (array[i] > lastItem) {
array[length-1] = array[i];
array[i] = lastItem;
lastItem = array[length - 1];
}
}
length--;
if (length > 1) lastItem = array[length - 1];
}
}
答案 0 :(得分:0)
你的算法使用冒泡排序,它取o(n ^ 2)。对于较大的输入,它可能很慢。为什么不使用快速排序来实现你想要的结果在O(nlogn)?
以下是一些代码,请注意,选择枢轴作为中间元素可能更好。
/**
* o(nlogn) - high probability otherwise o(n SQUARE)
*
*
* Choose a pivot value. We take the value of the middle element
* as pivot value, but it can be any value, which is in range of
* sorted values, even if it doesn't present in the array.
*
* Partition. Rearrange elements in such a way, that all elements
* which are lesser than the pivot go to the left part of the array
* and all elements greater than the pivot, go to the right part
* of the array. Values equal to the pivot can stay in any part
* of the array. Notice, that array may be divided in non-equal parts.
*
* Sort both parts. Apply quicksort algorithm recursively to the left
* and the right parts.
*
* @param input
*/
public void quickSort(int[] input, int start, int end){
if( start < end ){
int pindex = findParition(input, start, end);
quickSort(input, start, pindex-1);
quickSort(input, pindex+1, end);
}
}
/**
* findParition for quick sort
* @param input
* @param start
* @param end
* @return
*/
private int findParition(int[] input, int start, int end) {
int pivot = input[end];
int pindex = start;
for( int i = start; i < end; i++){
if( input[i] <= pivot ){
int temp = input[pindex];
input[pindex] = input[i];
input[i] = temp;
pindex++;
}
}
int temp = input[pindex];
input[pindex] = input[end];
input[end] = temp;
return pindex;
}
答案 1 :(得分:0)