비전공자 개발일기

Javascript bubble & selection & insertion sort 본문

Javascript

Javascript bubble & selection & insertion sort

HiroDaegu 2021. 9. 5. 01:29
728x90
SMALL

Bubble sort (버블 정렬)

두 인접한 원소를 검사하여 정렬

let array = [11, 2, 20, 3, 13 ,0, -20, 100, 1];
// [11, 2, 20, 3, 13 ,0, -20, 100, 1]를 버블정렬(내림차순)
console.log(array)
console.log("======================")
for (let i = 0; i < array.length - 1; i++) {
	let temp;
	for (let j = 0; j < array.length - 1 - i; j++){
			if (array[j] < array[j + 1]) {
				temp = array[j];
				array[j] = array[j + 1];
				array[j + 1] = temp;
				}
			console.log(` ${i + 1}회전 ${array}`)
			}
	console.log("======================")
	}


// [11, 2, 20, 3, 13 ,0, -20, 100, 1]를 버블정렬(오름차순)
console.log(array)
console.log("======================")
	for (let i = 0; i < array.length - 1; i++) {
		let temp;
		for (let j = 0; j < array.length - 1 - i; j++) {
			if (array[j] > array[j + 1]) {
				temp = array[j];
				array[j] = array[j + 1];
				array[j + 1] = temp;
				}
			console.log(` ${i + 1}회전 ${array}`)
			}
	console.log("======================")
	}

Selection sort (선택 정렬)

최소값(최대값)을 검색하여 배열의 왼쪽부터 순차적으로 정렬

 

// [11, 2, 20, 3, 13 ,0, -20, 100, 1]를 선택정렬(내림차순)
let array = [11, 2, 20, 3, 13 ,0, -20, 100, 1];
console.log(array);
console.log("======================");
let temVal;
for(let i = 0 ; i< array.length ; i++) {
	for(let j = i + 1 ; j < array.length  ; j++){
		if(array[j] >array[i]) {
			temVal = array[j];
			array[j] = array[i];
			array[i] = temVal;
			}
		console.log(` ${i + 1}회전 ${array}`);
		}
console.log("======================");
	}
    
document.write(array)
//[11, 2, 20, 3, 13 ,0, -20, 100, 1]를 선택정렬(오름차순) 
console.log(array);
console.log("======================");
let temVal2;
for(let i = 0 ; i< array.length ; i++) {
	for(let j = i + 1 ; j < array.length  ; j++){
		if(array[j] < array[i]) {
			temVal2 = array[j];
			array[j] = array[i];
			array[i] = temVal2;
			}
		console.log(` ${i + 1}회전 ${array}`);
		}
console.log("======================");
	}

Insertion sort(삽입 정렬)

배열의 요소를 차례대로 순회하면서, 이미 정렬된 배열과 비교하여 해당 요소를 올바른 위치에 삽입하는 것

const result = [11, 2, 20, 3, 13 ,0, -20, 100, 1]

for (let i = 1; i < result.length; i++) {
    let temp = result[i]
    let aux = i - 1

    // 배열 요소가 0보다 같거나 크고, 왼쪽 값이 더 클 때마다 계속해서 바꿔 나간다.
    while (aux >= 0 && result[aux] > temp) {
      result[aux + 1] = result[aux]
      aux--
    }
    result[aux + 1] = temp
  }
728x90
LIST

'Javascript' 카테고리의 다른 글

Javascript Drum  (0) 2021.09.08
Javascript Convert Rank + Calculate score  (0) 2021.09.07
Javascript For loop - tree  (0) 2021.09.04
Javascript NaN  (0) 2021.09.01
HTML JAVASCRIPT Select option Multiple  (0) 2021.08.27