【发布时间】:2015-04-11 14:57:04
【问题描述】:
今天在一次采访中,有人告诉我写一个程序,它将输出未排序数组中第 n 大的数字,
我用javascript解决了这个问题,程序如下,
var fn50 = function(){
var reverseSort = function(myArray,highest){
var x = 0,
y = 0,
z = 0,
temp = 0,
totalNum = myArray.length, // total numbers in array
flag = false, // is the numbers sorted in reverse while iteration
isAchieved = false; // whether we achieved the nth highest
while(x < totalNum){
y = x + 1; // start comparing 'yth' number which is next to 'xth' number.
if(y < totalNum){
// start comparing 'xth' with the next number, and if 'xth' number less than its next position number, just swipe them
for(z = y; z < totalNum; z++){
if(myArray[x] < myArray[z]){
temp = myArray[z];
myArray[z] = myArray[x];
myArray[x] = temp;
flag = true; // if number swiping done ?
}else{
continue;
}
}
}
if(flag){
flag = false;
}else{
x++; // x holds the max number in series, now move to next position to find next highest number
if(x > highest){ // if x is what the desired max number which we want flag it and break the loop to escape further iteration.
isAchieved = true;
}
}
if(isAchieved){
break;
}
}
print(myArray[(highest - 1)]);
};
reverseSort([12,56,78,34,11,100,95],4); // passing the unsorted array of number's, and finding the 4th highest number
};
fn50();
我得到了所需的输出,即上面数组中的答案是 56,这是第四大数字。
但面试官告诉了一个更好的解决方案。
您能否告诉我或给我一个提示,如何有更好的解决方案。 一些数据结构技术?
【问题讨论】:
-
嗯,这比对数组进行排序,然后从结果中取出第四个元素更复杂吗?如
arr.sort()[3]?既然语言已经有了,为什么还要编写自己的排序? -
@torazaburo 它必须是
arr.sort(function(a, b) { return a-b; }),因为.sort()进行词汇排序 -
@Andreas 当然,你是对的,那是伪代码。
标签: javascript arrays sorting