如果数组只包含O(n)
(k是常量)不同的元素,那么在最坏情况下运行时k ∈ ℕ>0
可以对数组进行排序吗?
假设需要有恒定的时间来比较其中包含n
个元素的数组。
首先,我想了解任务,他们想要什么?
我理解这个假设。但 k ∈ ℕ>0
(k是常数)不同的元素究竟是什么意思?
这是否意味着我们得到了一个数组,其大小为k
,因为它显示ℕ>0
数组大小不能为0
?那是对的吗?
如果是这样,我不太明白为什么他们不只是用n
元素代替数组而不是它。
无论如何,这就是我理解它的方式,我会说在最坏的情况下运行时间O(n)
不可能对这个数组进行排序,因为如果我们看一下桶排序/基数排序等,它可以在O(n*logn)
。
答案 0 :(得分:5)
如果你知道这些值,你可以通过将数字放入"桶和#34;来排序数组。对于每个值,您可以创建存储桶,并在迭代它时为该存储桶添加数字。您使用所有数字只需一次,因此可以在O(n)
例如,只有0-9的数字,您可以按以下方式对其进行排序
public class SortInBucket {
public static void main(String[] args) {
int[] x = {0,5,1,1,1,1,7,9,3,2,1,2,5,6};
System.out.println("Result of sorting: " + Arrays.toString(sortInBuckets(x)));
}
public static int[] sortInBuckets(int[] arr) {
List<List<Integer>> sortedNumbers = new ArrayList<>();
int[] sortedArr = new int[arr.length];
// create buckets 0 - 9
for (int i = 0; i < 10; i++) {
sortedNumbers.add(new ArrayList<>());
}
for (int i = 0; i < arr.length; i++) {
System.out.println("Found number " + arr[i] + " puting index " + i + " to bucket " + arr[i]);
sortedNumbers.get(arr[i]).add(i);
System.out.println("Bucket " + arr[i] + " is having " +sortedNumbers.get(arr[i]).size() + " numbers now." );
}
System.out.println();
System.out.println("The sortedNumbers (list with buckets) looks like following: " +sortedNumbers );
//just going through buckets and adding its numbers to sortedArr
int sortedIndex = 0;
for (List<Integer> bucket : sortedNumbers){
for (Integer num : bucket){
sortedArr[sortedIndex] = arr[num];
sortedIndex++;
}
}
return sortedArr;
}
}
上面的代码有这个输出
Found number 0 puting index 0 to bucket 0
Bucket 0 is having 1 numbers now.
Found number 5 puting index 1 to bucket 5
Bucket 5 is having 1 numbers now.
Found number 1 puting index 2 to bucket 1
Bucket 1 is having 1 numbers now.
Found number 1 puting index 3 to bucket 1
Bucket 1 is having 2 numbers now.
Found number 1 puting index 4 to bucket 1
Bucket 1 is having 3 numbers now.
Found number 1 puting index 5 to bucket 1
Bucket 1 is having 4 numbers now.
Found number 7 puting index 6 to bucket 7
Bucket 7 is having 1 numbers now.
Found number 9 puting index 7 to bucket 9
Bucket 9 is having 1 numbers now.
Found number 3 puting index 8 to bucket 3
Bucket 3 is having 1 numbers now.
Found number 2 puting index 9 to bucket 2
Bucket 2 is having 1 numbers now.
Found number 1 puting index 10 to bucket 1
Bucket 1 is having 5 numbers now.
Found number 2 puting index 11 to bucket 2
Bucket 2 is having 2 numbers now.
Found number 5 puting index 12 to bucket 5
Bucket 5 is having 2 numbers now.
Found number 6 puting index 13 to bucket 6
Bucket 6 is having 1 numbers now.
The sortedNumbers (list with buckets) looks like following: [[0], [2, 3, 4, 5, 10], [9, 11], [8], [], [1, 12], [13], [6], [], [7]]
Result of sorting: [0, 1, 1, 1, 1, 1, 2, 2, 3, 5, 5, 6, 7, 9]
正如JF Sebastian和Steve314所提到的,这样做的alghoritms称为Radix sort(更广义的alghorithm)或Counting sort(不是&#34; strong&#34;,但更简单,可用于此示例)。
答案 1 :(得分:1)
不,数组的大小为n
,但它可以包含重复的元素。数组中只有k
个唯一元素。 (换句话说,n - k
是数组中重复的数量。)