본문 바로가기

알고리즘

Sorting: Bubble Sort JavaScript로 풀기

728x90

/*

for (int i = 0; i < n; i++) {

    

    for (int j = 0; j < n - 1; j++) {

        // Swap adjacent elements if they are in decreasing order

        if (a[j] > a[j + 1]) {

            swap(a[j], a[j + 1]);

        }

    }

    

}

Given an array of integers, sort the array in ascending order using the Bubble Sort algorithm above. 

정수 배열이 주어지고, 배열을 위에 버블정렬 알고리즘을 이용하여 오름차순으로 정렬한다.

 

Once sorted, print the following three lines:

정렬하고나서, 아래 3줄을 출력하라

 

Array is sorted in numSwaps swaps., where numSwaps is the number of swaps that took place.

배열은 numSwaps 스왑으로 정렬된다. numSwaps은 스왑 횟수이다. 

 

First Element: firstElement, where firstElement is the first element in the sorted array.

첫번째 원소: firstElement는 정렬된 배열의 첫번째 원소이다.

 

Last Element: lastElement, where lastElement is the last element in the sorted array.

마지막 원소 : lastElement은 정렬된 배열의 마지막 원소이다.

 

swap    a       

0       [6,4,1]

1       [4,6,1]

2       [4,1,6]

3       [1,4,6]

 

일때

 

Array is sorted in 3 swaps.  

First Element: 1  

Last Element: 6  

 

이다.

 

버블정렬은 고딩때 배웠다

 

뭐 시간제한이 있다던가 이런 문제가 아니어서 다행히 떠오르는대로 막코딩하니 통과함.

 

*/

var a = [6,4,1]

var b = [1,4,6];

function countSwaps(a) {

    var cnt = 0;

    for(var i=0;i<a.length;i++){

        for(var j=i+1;j<a.length;j++){

            if(a[i]>a[j]){

                var tmp;

                tmp = a[i];

                a[i] = a[j];

                a[j] = tmp;

                cnt++;

            }

        }

    }

    console.log("Array is sorted in "+cnt+" swaps.  ");

    console.log("First Element: "+a[0]+"  ");

    console.log("Last Element: "+a[a.length-1]);

    return;

}

 

countSwaps(a)

728x90