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