Skip to content

Conversation

gagyeong17
Copy link

@gagyeong17 gagyeong17 commented Mar 24, 2024

우선 시간내로 과제를 완료하는게 어려울 것 같아서 아직 진행한 부분까지만 제출하고 이어서 더 하겠습니다.

삽입정렬의 경우 이해가 되었다고 생각했는데 구현하려고 하니까 잘 안되네용
강의 계속 반복해서 보면서 학습하겠습니다!
윤석님이 강의에서 풀이해주신 방법 말고 다르게 해보려고 했는데 다시 봐도 가장 쉽게 알려주신것같네여

Copy link
Contributor

@hannut91 hannut91 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

선택 정렬과 삽입 정렬까지 시도해 보셨군요! 퀵 정렬은 매우 중요한 알고리즘이니 꼭 익혀두셔야 합니다.

Comment on lines 1 to 16
const bubbleSort = (array) => {
let swapped = false;

for (let i = 0; i < array.length; i++) {
for (let j = 0; j < array.length - 1 - i; j++) {
if (array[j] > array[j + 1]) {
swapped = true;
let temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
if (!swapped) return array;
}
return array;
};
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이미 정렬되어 있으면 더 이상 볼 필요없이 빠르게 종료하려고 하신 것 같습니다. swapped가 최 상단에 있으면, 한 번 이라도 스왑이 일어나는 경우, 그 이후 단계에서 아무리 정렬되어 있어도 일찍 종료되지 않습니다.

다음과 같이 초기화를 해줘야 �한 번의 패스스루에서 한 번도 스왑이 일어나지 않은 경우 빠르게 종료됩니다.

const bubbleSort = (array) => {
  for (let i = 0; i < array.length; i++) {
    let swapped = false;

    for (let j = 0; j < array.length - 1 - i; j++) {
      if (array[j] > array[j + 1]) {
        swapped = true;
        let temp = array[j];
        array[j] = array[j + 1];
        array[j + 1] = temp;
      }
    }
    if (!swapped) return array;
  }
  return array;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants