Halo我试图冒泡排序二维数组,帮我调试。 可以在没有数组成功的情况下进行排序,但我需要使用一个无法解决的二维数组进行排序。
我需要每行独立的内容。 如果您可以使用任何其他排序算法,它也可以帮助
由于
//make a two dimensional array
function make2Darray(cols, rows){
var arr = new Array(cols);
for(var i = 0; i<arr.length; i++){
arr[i] = new Array(rows);
}
return arr;
}
var unsortedData = new Array([40516, 51028, 64212, 66516, 82597],
[35606, 85929, 89405, 79392, 38572]);
//Generate array
var row =2, column =5, d=0;
var unsorted= make2Darray(column,row);
for(var r=0; r<row; ++r){
for(var c =0; c<column; ++c){
unsorted[r][c] = unsortedData[d++];
}
}
function bubbleSort(arrayData)
{
document.write("<h3 class='text text-info'> Bubble Sort</h3>");
document.write("At the end of each iteration highest element is already sorted. <br />");
//Loop through to sort
for ( var count1 =0; count1<5; count1++)// outer loop loops (number of elements- 1) times
{
for ( var counter = 0; counter < 5; counter++)
{
//Compare elements and swap incase
if(arrayData[count1][counter] > arrayData[count1][counter+1])
{
//swap positions
var temp = arrayData[count1][counter];
arrayData[count1][counter] = arrayData[count1][counter+1];
arrayData[count1][counter+1] = temp;
}
}
}
return arrayData;
}
//pass data to sort to bubble sort function
//Determine execution time
var bs_start_time = performance.now();
var bs_array = bubbleSort(unsorted);
var c = bs_array.length;
//display sorted data
for(var i=0; i<row; i++){
for(var j = 0; j<column; j++){
document.write(bs_array[i][j] + ", ");
}
document.write("<br/>");
}
答案 0 :(得分:0)
我猜外部循环必须迭代到(count-1)= 4并且内部循环必须从count1 + 1迭代,因为你不应该交换已经排序的元素
for ( var count1 =0; count1<4; count1++)
{
for ( var counter = count1+1; counter < 5; counter++)
{
//Compare elements and swap incase
if(arrayData[count1][counter] > arrayData[count1][counter+1])
{
//swap positions
var temp = arrayData[count1][counter];
arrayData[count1][counter] = arrayData[count1][counter+1];
arrayData[count1][counter+1] = temp;
}
}
答案 1 :(得分:0)
//figured it out by adding a third loop
function bubbleSort(arrayData, r, c)
{
document.write("<h3 class='text text-info'> Bubble Sort</h3>");
document.write("At the end of each iteration highest element is already sorted. <br />");
//Loop through to sort
for ( var count =0; count<r; count++) // outer loop loops (number of elements- 1) times
{
for(var count2=c-1; count2>=0; count2--){
for ( var counter = 0; counter <=count2; counter++)
{
//Compare elements and swap incase
if(arrayData[count][counter] > arrayData[count][counter+1])
{
//swap positions
var temp = arrayData[count][counter];
arrayData[count][counter] = arrayData[count][counter+1];
arrayData[count][counter+1] = temp;
}
}
}
}
return arrayData;
}
//pass data to sort to bubble sort function
var bs_array = bubbleSort(unsorted, row, column);