인프런 워밍업 클럽 2기 - 특별미션

인프런 워밍업 클럽 2기 - 특별미션

function quickSort(arr, left, right) {
  if (left <= right) {
    let pivot = divide(arr, left, right);
    quickSort(arr, left, pivot - 1);
    quickSort(arr, pivot + 1, right);
  }
}

function divide(arr, left, right) {
  let pivot = arr[left].count;
  let leftStartIndex = left + 1;
  let rightStartIndex = right;

  while (leftStartIndex <= rightStartIndex) {
    while (leftStartIndex <= right && pivot >= arr[leftStartIndex].count) {
      leftStartIndex++;
    }

    while (rightStartIndex >= left + 1 && pivot <= arr[rightStartIndex].count) {
      rightStartIndex--;
    }

    if (leftStartIndex <= rightStartIndex) {
      swap(arr, leftStartIndex, rightStartIndex);
    }
  }

  swap(arr, left, rightStartIndex);
  return rightStartIndex;
}

function swap(arr, index1, index2) {
  let temp = arr[index1];
  arr[index1] = arr[index2];
  arr[index2] = temp;
}

let user1 = {
  name: "홍길동",
  count: 5,
};

let user2 = {
  name: "임꺽정",
  count: 4,
};

let user3 = {
  name: "이순신",
  count: 3,
};

let user4 = {
  name: "나",
  count: 1,
};

let user5 = {
  name: "짱구",
  count: 5,
};

let arr = [user1, user2, user3, user4, user5];

console.log("===== 정렬 전 =====");
console.log(arr);

quickSort(arr, 0, arr.length - 1);

if (arr[0].name === "나") {
  arr[0].count = 5;
}

console.log("===== 정렬 후 =====");
console.log(arr);

댓글을 작성해보세요.

채널톡 아이콘