CodeKata Week 5

Seob·2020년 9월 6일
0

Algorithms

목록 보기
8/8

Selection Sort(선택정렬)

정렬 알고리즘은 순서가 없던 데이터를 순서대로 바꾸어 나열하는 알고리즘입니다.
정렬을 하는 방법은 여러가지가 있는데, 그 중에 유명한 알고리즘은 아래 4가 있습니다.

  • 선택정렬
  • 버블정렬
  • 삽입정렬
  • 퀵정렬

오늘은 선택정렬을 배우겠습니다.
선택정렬은 정렬되지 않은 데이터 중 가장 작은 데이터를 선택해서
맨 앞에서부터 순서대로 정렬해 나가는 알고리즘입니다.

영어 설명 한 번 보시죠!
It has O(n2) time complexity, making it inefficient on large lists, and generally performs worse than the similar insertion sort.
Selection sort is noted for its simplicity, and it has performance advantages over more complicated algorithms in certain situations, particularly where auxiliary memory is limited.

예제를 통해 보겠습니다.

정렬을 해야하는 배열은 [7,5,4,2] 입니다.

첫 번째 loop에서는 index 0부터 3까지 확인하며 가장 작은 수를 찾습니다.
2 이므로 index 0의 7과 교체합니다. -> [2,5,4,7]

두 번째는 index 1부터 3까지 확인하며 가장 작은 수를 찾습니다.
4이므로 index 1의 5와 교체합니다 -> [2,4,5,7]

세 번째는 index 2부터 3까지.. 이런식으로 가장 작은 수를 선택해서 순서대로 교체하는 것을 선택정렬이라고 합니다.

  • code kata

nums라는 정렬되지 않은 숫자 배열을 주면, 오름차순(1,2,3..10) 으로 정렬된 배열을 return해주세요.
선택정렬 알고리즘으로 구현하셔야겠죠??

My Solution

const selectionSort = (nums) => {
let i = 0;
  while(i < nums.length) {
    let currMinIdx = i;
    for(let j = i + 1; j < nums.length ; j++) {
      if(nums[currMinIdx] > nums[j]) currMinIdx = j;
    }
    [nums[currMinIdx], nums[i]] = [nums[i], nums[currMinIdx]];
    i++;
  }
  return nums;
}

Model Solution

const selectionSort = (nums) => {
  for (let i = 0; i < nums.length; i++) {
    let minIdx = i;
    
    for (let j = i+1; j < nums.length; j++) {
      if (nums[minIdx] > nums[j]) {
        minIdx = j;
      }
    }
    
    let temp = nums[i];
    nums[i] = nums[minIdx];
    nums[minIdx] = temp;
  }
  
  return nums;
}

Bubble Sort(버블 정렬)

버블 정렬은 인접한 데이터를 교환해서 정렬하는 알고리즘입니다.
알고리즘의 정렬되는 모습이 마치 거품처럼 보인다고 해서 붙여진 이름입니다.
아래 그림을 한 번 봐주세요.
아마 알고리즘이 바로 이해되실 것입니다.

아래와 같은 정렬되지 않은 수가 있을 때, idex 0 <-> 1 부터 교환하기 시작합니다.
인접한 두 수를 비교하여 더 큰 것을 우측으로 이동시킵니다.
6 5 3 2 8
-> 5 6 3 2 8

그 다음은 index 1 <-> 2
5 6 3 2 8
-> 5 3 6 2 8

그 다음은 index 2 <-> 3
5 3 6 2 8
-> 5 3 2 6 8

그 다음은 index 3 <-> 4
5 3 2 6 8
-> 5 3 2 6 8
이렇게 제일 마지막 두 수 까지 비교하면, 제일 큰 수가 제일 마지막 index에 위치하는 것을 알 수 있습니다.

다시 처음부터 시작합니다.
5 3 2 6 8
-> 3 5 2 6 8

3 5 2 6 8
-> 3 2 5 6 8

3 2 5 6 8
-> 3 2 5 6 8
이번 교환에는 index 2까지 비교하고 멈추면 됩니다.
마지막 index는 이미 제일 큰 수가 정렬된 상태이기 때문입니다.
이런식으로 계속 비교하고 교체하면 됩니다.!

  • 코드카타
    nums라는 배열을 주면, 버블정렬 알고리즘으로 배열을 정렬해주세요.

My Solution

const bubbleSort = nums => {
  for (i in nums) {
    for (let i = 0; i < nums.length-1; i++ ) {
      if (nums[i] > nums[i+1]) {
        [nums[i], nums[i+1]] = [nums[i+1], nums[i]]
      }
    }
  }
  return nums
}

Model Solution

const bubbleSort = nums => {
  for (let i = 0; i < nums.length; i++) {
    for (let j = 0; j < nums.length-i-1; j++) {
      if (nums[j] > nums[j+1]) {
        let temp = nums[j+1];
        nums[j+1] = nums[j];
        nums[j] = temp;
      }
    }
  }
  
  return nums;
}

console.log(bubbleSort([2,1]))

Recursion(재귀)

이전에 재귀에 대해 이미 배운바 있습니다.
오늘은 재귀를 사용해서 문제를 풀어주세요.

str 이라는 'string'을 넘겨주면 글자순서를 바꿔서 return해주세요.
reverse 메서드 사용은 당연히 금지입니다!

input: 'hello'
output: 'olleh'

*힌트
아래의 코드가 어색한 것은 아니겠죠?
(함수의 return에 string을 붙여서 사용하는 것)

function getName(name) {
  return name;
}

console.log(getName('김')+'님');

My Solution

const reverseString = str => {
  if(str.length === 1) return str;
  if(str.length === 2) return str[1] + str[0];
  let half = parseInt(str.length/2);
  return reverseString(str.substring(half + 1, str.length)) + reverseString(str.substring(0, half + 1));
}

Model Solution

const reverseString = str => {
  if (str === '') {
    return '';
  } else {
    return reverseString(str.substr(1)) + str.charAt(0);
  }
}

// 한줄처리
// const reverseString = str => {
//   return str === '' ? '' : reverseString(str.substr(1)) + str.charAt(0);
// }
profile
Hello, world!

0개의 댓글