[CodeWars] Bubblesort Once

Bubblesort Algorithm


The Bubblesort Algorithm is one of many algorithms used to sort a list of similar items (e.g. all numbers or all letters) into either ascending order or descending order. Given a list (e.g.):

{9, 7, 5, 3, 1, 2, 4, 6, 8}

To sort this list in ascending order using Bubblesort, you first have to compare the first two terms of the list. If the first term is larger than the second term, you perform a swap. The list then becomes:

{7, 9, 5, 3, 1, 2, 4, 6, 8} // The "9" and "7" have been swapped because 9 is larger than 7 and thus 9 should be after 7

You then proceed by comparing the 2nd and 3rd terms, performing a swap when necessary, and then the 3rd and 4th term, then the 4th and 5th term, etc. etc. When you reach the end of the list, it is said that you have completed 1 complete pass.


Given an array of integers, your function bubblesortOnce/bubblesort_once/BubblesortOnce (or equivalent, depending on your language’s naming conventions) should return a newarray equivalent to performing exactly 1 complete pass on the original array. Your function should be pure, i.e. it should not mutate the input array.

My Solution

std::vector<int> bubbleSortOnce(const std::vector<int> &input)
    std::vector<int> result(input);

    for (int i = 0; i < result.size()  1++i)
        if (result[i] > result[i + 1])
            std::swap(result[i], result[i + 1]);

    return result;

Bubble alignment is an alignment that repeats the loop of above code n times. The results only run once, so you can resolve them by removing the repetition.

글쓴이: BakJH

Student of Daedeok SW Meister Highschool, in Korea.

답글 남기기

아래 항목을 채우거나 오른쪽 아이콘 중 하나를 클릭하여 로그 인 하세요:

WordPress.com 로고

WordPress.com의 계정을 사용하여 댓글을 남깁니다. 로그아웃 /  변경 )

Google photo

Google의 계정을 사용하여 댓글을 남깁니다. 로그아웃 /  변경 )

Twitter 사진

Twitter의 계정을 사용하여 댓글을 남깁니다. 로그아웃 /  변경 )

Facebook 사진

Facebook의 계정을 사용하여 댓글을 남깁니다. 로그아웃 /  변경 )

%s에 연결하는 중