31

On Binary Search

 4 years ago
source link: https://www.tuicool.com/articles/uUj2aeV
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Introduction

When probed by the Google boss on how to sort 1 million integers, former U.S. President Barack Obama, provided the correct answer. Or rather, he stated that you should not use bubble sort .

Consider this code:

function bubbleSort(yourArr) {
  let isDone = false;
  while (!isDone) {
    isDone = true;
    for (let i = 1; i<yourArr.length; i++) {
      if (yourArr[i-1] > yourArr[i]) {
        isDone = false;
        [yourArr[i-1], yourArr[i]] = [yourArr[i], yourArr[i-1]];
      }
    }
  }
  return yourArr;
}
const listOfPhilosophers = ['Wittgenstein', 'Kant', 'Foucault', 'Agamben', 'Deleuze'];
const  azSortedListOfPhilosophers = bubbleSort(listOfPhilosophers);

This is a standard implementation of bubble sort.

It has deficiencies. For instance, since it sorts according to sign position in the ASCII table, “adam” would come after Wittgenstein and it would be more reasonable to have linked to the native sort function.

But is this algorithm efficient?

If the element to be found in the array is somewhere at the end, almost every element in the array must be visited. And if you sort 1 million integers with bubble sort it would take a very long time in comparison with other solutions. Obama was right.

Binary search activates similar questions and options.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK