例如:
这是面试需要的,只需要提供一个伪代码。
int A[] = {3,2,1,2,3,2,1,3,1,2,3};
如何高效地对这个数组进行排序?这是面试需要的,只需要提供一个伪代码。
int A[] = {3,2,1,2,3,2,1,3,1,2,3};
如何高效地对这个数组进行排序?你尝试过查看维基百科吗?- http://en.wikipedia.org/wiki/Sorting_algorithm
int[] intArray = new int[9] {3,2,1,2,3,2,1,3,1 };
Array.Sort(intArray);
// write array
foreach (int i in intArray) Console.Write("{0}, ", i.ToString());
让我们来解决这个问题,我们有一个只包含两个数字的数组。[1,2,1,2,2,2,1,1]
我们可以在一次遍历中以O(n)的时间复杂度进行排序,并进行最小交换,如果: 我们从左右两侧开始使用两个指针,直到它们相遇。 如果左边的元素比右边的元素大,则交换左边的元素和右边的元素。(升序排序)
我们可以进行另一次遍历,处理三个数字(k-1次遍历)。在第一次遍历中,我们将1移动到它们的最终位置,在第二次遍历中,我们将2移动到它们的最终位置。
def start = 0, end = array.size() - 1;
// Pass 1, move lowest order element (1) to their final position
while (start < end) {
// first element from left which is not 1
for ( ; Array[start] == 1 && start < end ; start++);
// first element from right which IS 1
for ( ; Array[end] != 1 && start < end ; end--);
if (start < end) swap(start, end);
}
// In second pass we can do 10,15
// We can extend this using recurion, for sorting domain = k, we need k-1 recurions
def DNF(input,length):
high = length - 1
p = 0
i = 0
while i <= high:
if input[i] == 0:
input[i],input[p]=input[p],input[i]
p = p+1
i = i+1
elif input[i] == 2:
input[i],input[high]=input[high],input[i]
high = high-1
else:
i = i+1
input = [0,1,2,2,1,0]
print "input: ", input
DNF(input,len(input))
print "output: ", input
fun sortNums(smallestIndex,largestIndex,array,currentIndex){
if(currentIndex >= array.size)
return
if (array[currentIndex] == 1){
You have found the smallest element, now increase the smallestIndex
//You need to put this element to left side of the array at the smallestIndex position.
//You can simply swap(smallestIndex, currentIndex)
// The catch here is you should not swap it if it's already on the left side
//recursive call
sortNums(smallestIndex,largestIndex,array,currentIndex or currentIndex+1)// Now the task of incrementing current Index in recursive call depends on the element at currentIndex. if it's 3, then you might want to let the fate of currentIndex decided by recursive function else simply increment by 1 and move further
} else if (array[currentInde]==3){
// same logic but you need to add it at end
}
}
您可以通过sortNums(smallestIndex=-1, largestIndex=array.size, array, currentIndex=0)启动递归函数
您可以在此处找到示例代码 代码链接
//Bubble sort for unsorted array - algorithm
public void bubleSort(int arr[], int n) { //n is the length of an array
int temp;
for(int i = 0; i <= n-2; i++){
for(int j = 0; j <= (n-2-i); j++){
if(arr[j] > arr[j +1]){
temp = arr[j];
arr[j] = arr[j +1];
arr[j + 1] = temp;
}
}
}