From 0e919d88f3a5ec5dd36c95a2b7bf5e9a74dfc155 Mon Sep 17 00:00:00 2001 From: Dan Sajjad Date: Sun, 23 Oct 2016 00:29:14 -0700 Subject: [PATCH] Convert code from insertion sort logic to bubble sort Collection elements should bubble up to the right in a bubble sort. The compares should be made with all elements to the right. In an insertion sort elements will sink towards the left and compares are made with all elements to the left. Please see step by step compares: https://en.wikipedia.org/wiki/Bubble_sort --- src/sorting/bubblesort.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/sorting/bubblesort.js b/src/sorting/bubblesort.js index 7b5440ee..ba55e00d 100644 --- a/src/sorting/bubblesort.js +++ b/src/sorting/bubblesort.js @@ -25,12 +25,12 @@ function bubbleSort(array, cmp) { cmp = cmp || comparator; var temp; - for (var i = 0; i < array.length; i += 1) { - for (var j = i; j > 0; j -= 1) { - if (cmp(array[j], array[j - 1]) < 0) { + for (var i = 0; i < array.length - 1; i += 1) { + for (var j = 0; j < array.length - 1 - i; j += 1) { + if (cmp(array[j + 1], array[j]) < 0) { temp = array[j]; - array[j] = array[j - 1]; - array[j - 1] = temp; + array[j] = array[j + 1]; + array[j + 1] = temp; } } }