Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【每日一题】- 2020-03-23 - 如何优化冒泡排序在数组近乎有序的情况下的效率 #324

Open
azl397985856 opened this issue Mar 23, 2020 · 4 comments

Comments

@azl397985856
Copy link
Owner

@azl397985856 azl397985856 commented Mar 23, 2020

对于数组[1, 2, 3, 4] 和 [4, 3, 2, 1] 你的冒泡排序算法是否都能获得不错的效率?

@twinkle77
Copy link

@twinkle77 twinkle77 commented Mar 23, 2020

  • 设置一个标记位来标记是否发生了交换,如果没有发生交换就提前结束;
  • 记录“最后发生交换”的位置,该位置后面的已经排序好了,作为下一趟比较结束的位置。
function advanceBubbleSort1(arr){
    let flag;
    for(let i = 1, len = arr.length; i <= len - 1; i++){
        flag = false; //每轮一开始都必须重新设置标志
        for(let j = 0; j < len - i; j++){
            if(arr[j] > arr[j + 1]){
                temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
                flag = true;
            }
        }
        if(flag === false){
            break;
        }
    }
    return arr;
}


function advanceBubbleSort2(arr){
    let k = 0;
    let n = arr.length;
    for(let i = 1, len = arr.length; i <= len - 1; i++){
        k = n;     //每一轮 都需重新设置到 上一轮冒泡结束的位置
        n = 0;      
        for(let j = 0; j < k - 1; j++){
            if(arr[j] > arr[j + 1]){
                temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
                n = j + 1;
            }
        }
    }
    return arr;
}
@azl397985856
Copy link
Owner Author

@azl397985856 azl397985856 commented Mar 23, 2020

@twinkle77 没明白你的算法是如何保证正向有序和逆向有序都取得不错效率的? 你的算法难道不是只可以处理其中一种情况么?

@twinkle77
Copy link

@twinkle77 twinkle77 commented Mar 23, 2020

确实不对 没考虑到逆向有序的情况 @azl397985856

@hzgotb
Copy link

@hzgotb hzgotb commented Apr 1, 2020

function bubbleSort(array, asc = true) {
  const result = Array.from(array);
  const count = array.length - 1;
  let border = count;
  let borderTemp = 0;
  for (let i = 0; i < count; i += 1) {
    let isSorted = true;
    for (let j = 0; j < border; j += 1) {
      if (asc ? (result[j] > result[j+1]) : (result[j] < result[j+1])) {
        [result[j], result[j+1]] = [result[j+1], result[j]];
        isSorted = false;
        borderTemp = j;
      }
      console.log(`第${i+1}次循环的第${j+1}次对比:`, result.toString());
    }
    if (isSorted) {
      break;
    }
    border = borderTemp;
  }
  return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
3 participants
You can’t perform that action at this time.