comparator
함수를 인자로 받음comparator
함수를 사용해서 어떻게 정렬할 것인지 JavaScript에 알림comparator
함수는 반환값을 기준으로 요소 한 쌍의 정렬 순서를 정함function numberCompare(num1, num2) {
return num1 - num2;
}
[6, 4, 15, 10].sort(numberCompare); // [4, 6, 10, 15]
function numberCompare2(num1, num2) {
return num2 - num1;
}
[6, 4, 15, 10].sort(numberCompare2); // [15, 10, 6, 4]
function compareByLen(str1, str2) {
return str1.length - str2.length;
}
['a', 'abc', 'abcde', 'aa'].sort(compareByLen); // ['a', 'aa', 'abc', 'abcde']
// ES5
function swap(arr, idx1, idx2) {
var temp = arr[idx1];
arr[idx1] = arr[idx2];
arr[idx2] = temp;
}
// ES2015
function swap(arr, idx1, idx2) {
[arr[idx1], arr[idx2]] = [arr[idx2], arr[idx1]];
}
// ES5
function bubbleSort(arr){
for(var i = arr.length; i > 0; i--){
for(var j = 0; j < i - 1; j++){
console.log(arr, arr[j], arr[j+1]);
if(arr[j] > arr[j+1]){
var temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
return arr;
}
// ES2016
function bubbleSort(arr){
const swap = (arr, idx1, idx2) => {
[arr[idx1], arr[idx2]] = [arr[idx2], arr[idx1]];
}
for (var i = arr.length; i > 0; i--) {
for (var j = 0; j < i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr, j, i + 1);
}
}
}
return arr;
}
// ES5
function bubbleSort(arr){
var noSwaps;
for (var i = arr.length; i > 0; i--) {
var noSwaps = true;
for (var j = 0; j < i - 1; j++) {
if (arr[j] > arr[j + 1]) {
var temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
noSwaps = false;
}
}
if (noSwaps) break;
}
return arr;
}
// ES2016
function bubbleSort(arr){
const swap = (arr, idx1, idx2) => {
[arr[idx1], arr[idx2]] = [arr[idx2], arr[idx1]];
}
let noSwaps;
for (var i = arr.length; i > 0; i--) {
noSwaps = true;
for (var j = 0; j < i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr, j, j + 1);
noSwaps = false;
}
}
if (noSwaps) break;
}
return arr;
}
// ES5
function selectionSort(arr){
for (var i = 0; i < arr.length; i++) {
var lowest = i;
for (var j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[lowest]) {
lowest = j;
}
}
if (i !== lowest) {
var temp = arr[i];
arr[i] = arr[lowest];
arr[lowest] = temp;
}
}
return arr;
}
// ES2015
function selectionSort(arr){
const swap = (arr, idx1, idx2) => [arr[idx1], arr[idx2]] = [arr[idx2], arr[idx1]];
for (var i = 0; i < arr.length; i++) {
let lowest = i;
for (let j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[lowest]) {
lowest = j;
}
}
if (i !== lowest) swap(arr, i, lowest);
}
return arr;
}
function insertionSort(arr){
for (let i = 1; i < arr.length; i++) {
let currentVal = arr[i];
for (let j = i - 1; j >= 0 && arr[j] > currentVal; j--) {
arr[j + 1] = arr[j];
}
arr[j + 1] = currentVal;
}
}
Algorithm | Time Complexity (Best) | Time Complexity (Average) | Time Complexity (Worst) | Space Complexity |
---|---|---|---|---|
Bubble Sort | O(N) | O(N^2) | O(N^2) | O(1) |
Insertion Sort | O(N) | O(N^2) | O(N^2) | O(1) |
Selection Sort | O(N^2) | O(N^2) | O(N^2) | O(1) |
Best Case for Bubble, Insertion, Selection Sort
Space Complexity for for Bubble, Insertion, Selection Sort