Algorithms: Implement Insertion Sort
This commit is contained in:
		
							parent
							
								
									b7be24f4c6
								
							
						
					
					
						commit
						f0b0d87d05
					
				
							
								
								
									
										22
									
								
								Algorithms/insertionSort.js
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										22
									
								
								Algorithms/insertionSort.js
									
									
									
									
									
										Normal file
									
								
							@ -0,0 +1,22 @@
 | 
				
			|||||||
 | 
					// https://www.freecodecamp.org/learn/coding-interview-prep/algorithms/implement-insertion-sort
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					function insertionSort(array) {
 | 
				
			||||||
 | 
					  // Only change code below this line
 | 
				
			||||||
 | 
					  const swap = (array, i, j) => {
 | 
				
			||||||
 | 
					    const temp = array[i];
 | 
				
			||||||
 | 
					    array[i] = array[j];
 | 
				
			||||||
 | 
					    array[j] = temp;
 | 
				
			||||||
 | 
					  };
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					  for (let i = 0; i < array.length; i++) {
 | 
				
			||||||
 | 
					    for (let j = i; j > 0; j--) {
 | 
				
			||||||
 | 
					      if (array[j] < array[j - 1]) {
 | 
				
			||||||
 | 
					        swap(array, j, j - 1);
 | 
				
			||||||
 | 
					      } else {
 | 
				
			||||||
 | 
					        break;
 | 
				
			||||||
 | 
					      }
 | 
				
			||||||
 | 
					    }
 | 
				
			||||||
 | 
					  }
 | 
				
			||||||
 | 
					  return array;
 | 
				
			||||||
 | 
					  // Only change code above this line
 | 
				
			||||||
 | 
					}
 | 
				
			||||||
		Loading…
	
		Reference in New Issue
	
	Block a user