Sort Flashcards

1
Q

Sort the given array using insertion sort – [3,2,5,1,4]?

A
function insertionSort(array){
 for(var i = 0; i \< array.length; i++){
 for(var j = 0; j \< i; j++){
 if(array[i] \< array[j]){
 var temp = array[i]
 array[i] = array[j]
 array[j] = temp
 }
 }
 }
 return array
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Sort the given array using quicksort – [3,2,5,1,4]?

A
function quickSort(array){
 if(array.length === 0){
 return [];
 }
 var left = [];
 var right = [];
 var pivot = array[0];
 for(var i = 1; i \< array.length; i++){
 if(array[i] \< pivot){
 left.push(array[i])
 }
 else{
 right.push(array[i])
 }
 }
 return quickSort(left).concat(pivot, quickSort(right));
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Sort the given array using mergesort –[3,2,5,1,4]?

A
function mergeSort(array){
 if(array.length \< 2) {
 return array;
 }
 var mid = Math.floor(array.length / 2);
 var left = array.slice(0, mid);
 var right = array.slice(mid);
 return merge(mergeSort(left), mergeSort(right))
}
function merge(left, right){
 var result = [];
 var indexLeft = 0;
 var indexRight = 0;
 while(indexLeft \< left.length && indexRight \< right.length){
 if(left[indexLeft] \< right[indexRight]){
 result.push(left[indexLeft++]);
 }
 else {
 result.push(right[indexRight++])
 }
 }
 while(indexLeft \< left.length){
 result.push(left[indexLeft++]);
 }
 while(indexRight \< right.length) {
 result.push(right[indexRight++])
 }

return result;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly