250x250
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- 백엔드
- xcode
- php
- keyframes
- 비전공자
- Animation
- html5
- front-end
- iOS 개발자
- 비전공 개발자
- ipad
- 개발자
- jQuery
- image
- iPhone
- IOS
- javascript
- css3
- hover
- effect
- CSS
- MAC
- 자바스크립트
- 프론트엔드
- HTML
- SWIFT
- 풀스택
- react
- 애니메이션
- button
Archives
- Today
- Total
비전공자 개발일기
Javascript bubble & selection & insertion sort 본문
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 |