Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

자바스크립트 버블 정렬로 객체 배열을 가격 기준으로 정렬하는 방법

신발(Shoe) 객체를 생성하는 생성자 클래스가 있다고 가정해 보겠습니다.

class Shoe {
    constructor(name, price, type) {
        this.name = name;
        this.price = price;
        this.type = type;
    }
};

이 클래스를 활용하면 다음과 같이 여러 개의 객체로 배열을 채울 수 있습니다.

const arr = [
    new Shoe('Nike AirMax 90', '120', 'Casual'),
    new Shoe('Jordan Retro 1', '110', 'Casual'),
    new Shoe('Jadon Doc Martens', '250', 'Seasonal boots'),
    new Shoe('Adidas X Ghosted', '110', 'Athletic'),
    new Shoe('Nike Vapourmax Flyknit', '250', 'Casual'),
    new Shoe('Aldo Loafers', '130', 'Formal'),
    new Shoe('Timberlands', '199', 'Seasonal boots'),
    new Shoe('Converse High Tops', '70', 'Casual'),
    new Shoe('Converse Low Tops', '80', 'Casual'),
    new Shoe('Adidas NMDs', '110', 'Athletic'),
    new Shoe('Heels', '130', 'Formal'),
    new Shoe('Nike AirForce', '150', 'Casual')
];

이제 요구 사항은 버블 정렬(Bubble Sort) 알고리즘을 정확히 활용하여 이 객체 배열을 price(가격) 속성을 기준으로 오름차순으로 정렬하는 자바스크립트 함수를 작성하는 것입니다.

버블 정렬의 동작 원리

버블 정렬은 인접한 두 요소를 서로 비교한 뒤, 순서가 잘못되어 있으면 위치를 교환(swap)하는 방식으로 동작하는 가장 기본적인 정렬 알고리즘입니다. 배열 전체를 반복해서 순회하며 더 이상 교환이 발생하지 않을 때까지 과정을 반복하면 배열이 완전히 정렬됩니다.

이번 예제에서 주목할 점은 두 가지입니다.
첫째, 가격 값이 문자열('120')로 저장되어 있기 때문에 단항 더하기 연산자(+)를 사용해 숫자로 변환한 후 비교합니다.
둘째, swapped 플래그 변수를 활용해 한 번의 순회에서 교환이 일어나지 않으면 반복을 종료함으로써 불필요한 연산을 줄였습니다.

예제 코드

전체 구현 코드는 다음과 같습니다.

class Shoe {
    constructor(name, price, type) {
        this.name = name;
        this.price = price;
        this.type = type;
    }
};
const arr = [
    new Shoe('Nike AirMax 90', '120', 'Casual'),
    new Shoe('Jordan Retro 1', '110', 'Casual'),
    new Shoe('Jadon Doc Martens', '250', 'Seasonal boots'),
    new Shoe('Adidas X Ghosted', '110', 'Athletic'),
    new Shoe('Nike Vapourmax Flyknit', '250', 'Casual'),
    new Shoe('Aldo Loafers', '130', 'Formal'),
    new Shoe('Timberlands', '199', 'Seasonal boots'),
    new Shoe('Converse High Tops', '70', 'Casual'),
    new Shoe('Converse Low Tops', '80', 'Casual'),
    new Shoe('Adidas NMDs', '110', 'Athletic'),
    new Shoe('Heels', '130', 'Formal'),
    new Shoe('Nike AirForce', '150', 'Casual')
];
const bubbleSort = (arr = []) => {
    let swapped;
    do {
        swapped = false;
        for (let i = 0; i < arr.length - 1; i++) {
            if (+arr[i].price > +arr[i + 1].price) {
                let temp = arr[i];
                arr[i] = arr[i + 1];
                arr[i + 1] = temp;
                swapped = true;
            };
        };
    } while (swapped);
}
bubbleSort(arr);
console.log(arr);

출력 결과

위 코드를 실행하면 콘솔에 다음과 같이 가격이 낮은 순서대로 정렬된 배열이 출력됩니다.

[
    Shoe { name: 'Converse High Tops', price: '70', type: 'Casual' },
    Shoe { name: 'Converse Low Tops', price: '80', type: 'Casual' },
    Shoe { name: 'Jordan Retro 1', price: '110', type: 'Casual' },
    Shoe { name: 'Adidas X Ghosted', price: '110', type: 'Athletic' },
    Shoe { name: 'Adidas NMDs', price: '110', type: 'Athletic' },
    Shoe { name: 'Nike AirMax 90', price: '120', type: 'Casual' },
    Shoe { name: 'Aldo Loafers', price: '130', type: 'Formal' },
    Shoe { name: 'Heels', price: '130', type: 'Formal' },
    Shoe { name: 'Nike AirForce', price: '150', type: 'Casual' },
    Shoe { name: 'Timberlands', price: '199', type: 'Seasonal boots' },
    Shoe { name: 'Jadon Doc Martens', price: '250', type: 'Seasonal boots'},
    Shoe { name: 'Nike Vapourmax Flyknit', price: '250', type: 'Casual' }
]