공지: 기존 사이트는 old.codingdojang.com에서 확인할 수 있으며, 2026년 8월 3일 종료됩니다.
이 페이지는 코딩도장 데이터의 읽기 전용 정적 보관본입니다.

Bubble Sort

출저 : http://www.codeabbey.com/index/task_view/bubble-sort

배열을 소팅하는 것은 초보 프로그래머에게 유명한 문제이며 전문적인 프로그래밍(데이터베이스, 라이브러리등)에서도 매우 중요하게 다루어 진다.

소팅은 비교에 기반을 두어 배열을 재 정렬하는 방법이다. 다음의 배열을 생각해 보자.

a = [3, 1, 4, 1, 5, 9, 2, 6]

우리는 이 배열을 크기 순서대로 정렬하고 싶다. (좌측의 요소는 우측의 요소보다 작거나 같아야 한다.)

수학적으로 표현하자면 다음과 같다.

i < j, a[i] <= a[j]

인덱스 i가 j보다 작은 경우 배열의 값인 a[i]는 a[j]값보다 작거나 같아야 한다.

버블소트(Bubble Sort)는 이러한 소팅을 하기 위한 가장 간단한 방법 중 하나이다. 그 간단한 방법은 다음과 같다:

  1. 배열을 따라가며 인접한 쌍을 찾는다. (N개의 배열이 있을 경우 N-1개의 쌍이 존재하게 된다)
  2. 만약 a[i] <= a[i+1] 을 만족하지 않는 쌍을 찾게 되면 두 개의 값을 서로 바꾸어준다. (Swap)
  3. 더 이상 바꾸어야 할 쌍이 존재하지 않을 때까지 1번, 2번을 반복한다. (Loop)

i와 j라는 인덱스를 가진 두 개의 값을 서로 바꾸기(Swap) 위해서는 몇가지 방법이 있는데 임시 변수를 사용하는 예는 다음과 같다:

t = a[i]
a[i] = a[j]
a[j] = t

입력과 출력

입력 데이터의 첫번째 라인은 배열의 갯수를 의미하며 두번째 라인은 배열의 요소값을 의미한다.

출력 데이터는 두개의 값으로 이루어진다.
첫번째 값은 배열을 따라 진행(Loop)한 횟수이며 두번째 값은 Swap이 발생한 총 횟수이다.

다음은 입출력 예제이다:

input data:
8
3 1 4 1 5 9 2 6

answer:
5 8
bubble-sort

2014/05/08 18:07

pahkey

입출력 예제에서.. Swap없이 그냥 지나친 총 횟수가 5가 아닌것 같은데요^^; 20 혹은 16이 아닐까요? - Katherine, 2014/05/09 01:10
Swap 없이 그냥 지나친 총 횟수 -> 진행한 총 횟수 인거같아요 - Starleaguer, 2014/05/09 01:04
네 원문에서 출력 데이터 첫번째 값은 number of passes perfromed (performed의 오타인듯해요ㅎㅎ). 배열 따라가기를 진행한 횟수가 맞네요^^ Swap여부와는 상관이 없고, 배열을 처음부터 끝까지 한 번 따라간 횟수요^^; - Katherine, 2014/05/09 01:17
@Katherine님, @Starleaguer님 알려주셔서 감사합니다. 오역을 했네요, 본문은 수정해 놓았습니다. - pahkey, 2014/05/09 08:41

105개의 풀이가 있습니다.

각 item에 대해서, 정렬 전의 위치와 정렬 후의 위치를 알아냅니다. 이는 아무 정렬 알고리즘이나 사용하면 되므로 O(n lg n)에 할 수 있습니다.

한번 swap이 일어날 때마다 위치가 1칸씩 바뀌므로, 정렬 전의 위치와 정렬 후의 위치가 몇 칸 떨어져 있는지를 알면 각각의 item이 몇 번 움직였는지 알 수 있겠죠.

Bubble sort는 모든 원소들이 정렬되어 한 번도 swap이 발생하지 않으면 종료되므로, 가장 거리가 먼 원소가 자리를 찾아가기까지 몇 번 움직이는지를 알면 구할 수 있겠죠?

전체 swap 횟수들은 각 item의 swap 회수를 더하면 되겠죠. 그러나 주의할 점은, 한번 swap이 일어날 때마다 2개의 item 위치가 바뀌므로 전체 횟수는 반으로 나눠야 합니다.

이 과정에서 정렬이 가장 시간복잡도가 높은 과정으로 전체 시간복잡도는 O(N lg N)이 됩니다. Bubble sort를 naive하게 구현한 경우 O(N^2)인데 이와는 수행속도의 차이가 어마어마하겠지요.

#include<iostream>
#include<vector>
#include<utility>
#include<algorithm>
using namespace std;

vector<pair<int, int> > v;

void input(){
    int i;
    int N;
    cin >> N;
    for(i=0;i<N;++i){
        int t;
        cin >> t;
        v.push_back(make_pair(t, i));
    }
}

inline int abs(int a){return a<0?-a:a;}

int main(){
    input();

    sort(v.begin(), v.end());

    int swap_cnt = 0, max_dist = 0;
    int i;

    for(i=0; i < v.size(); ++i){
        int dist = abs(v[i].second - i);
        if(max_dist < dist) max_dist = dist;

        swap_cnt += dist;
    }

    cout << max_dist+1 << " " << swap_cnt/2 << "\n";

    return 0;
}

2014/05/19 20:48

Kim Jaeju

펄입니다

my@input=<STDIN>;
my$count=$input[0];
my@data=split //,$input[1];
my$swap_count;
my $i;
for($i=0;$swap_count<$count;$i++){
    my $j=$i%($count-1);
    unless($data[$j]<=$data[$j+1])
    {
        my$t=$data[$j];
        $data[$j]=$data[$j+1];
        $data[$j+1]=$t;
        $swap_count++;
    }
}
@a=($i%$count,$count);
print "@a\n";

2014/12/20 11:56

이병곤

JAVA입니다

package bubble_sort;
import java.util.Scanner;
public class Swap {

    public static void main(String[] args) {
        Scanner in=new Scanner(System.in);
        System.out.println("input data:");
        int i,j,t,pass=0,swap=0,lineswap, N=in.nextInt();
        int a[]=new int[N];
        for(i=0;i<N;i++) a[i]=in.nextInt();
        do{
            pass++; lineswap=0;
            for(i=0;i<N-1;i++){
                if(a[i]>a[i+1]){
                    t=a[i];
                    a[i]=a[i+1];
                    a[i+1]=t;
                    swap++; lineswap++;
                }
                /*Printing the process*/
                // for(j=0;j<N;j++) System.out.print(((j==i)?"[":((j!=i+2)?" ":""))+a[j]+((j==i+1)?"]":"") );
                // System.out.println();
            }
        }while(lineswap>0);
        System.out.println("\nanswer:\n"+pass+" "+swap);
    }
}

2014/05/09 01:24

Katherine

python.

# bubble sort

def bubble_sort(a):
    pass_count = 0
    swap_count = 0
    while True:
        swap = 0
        for i in range(len(a)-1):
            if a[i] > a[i+1]:
                a[i], a[i+1] = a[i+1], a[i]
                swap+=1
        pass_count += 1
        if swap:
            swap_count += swap
        else:
            break
    return pass_count, swap_count, a


print bubble_sort([3, 1, 4, 1, 5, 9, 2, 6])

2014/05/09 09:12

pahkey

class BubbleSort():
    def bsort(self, num):
        t = 0
        swap=0
        for i in range(len(num)):
            for j in range(len(num)-1):
                if num[j]>num[j+1]:
                    t=num[j]
                    num[j]=num[j+1]
                    num[j+1]=t
                    swap+=1
            print num, swap

a=BubbleSort()
a.bsort([3, 1, 4, 1, 5, 9, 2, 6])

2014/05/20 11:03

Jaewon Kim

C#으로 작성했습니다. 재귀함수를 사용했고, 매번 재귀함수를 돌릴 때마다 length - 1을 넣었습니다.

using System;
using System.Collections.Generic;

        public void BubbleSort(List<int> inputs, int n, int loop = 1, int swap = 0)
        {
            var isSorted = true;
            for (int i = 0; i < n - 1; i++)
            {
                if (inputs[i] > inputs[i + 1])
                {
                    isSorted = false;
                    var temp = inputs[i];
                    inputs[i] = inputs[i + 1];
                    inputs[i + 1] = temp;
                    swap++;
                }
            }
            if (isSorted) Console.WriteLine("Loop: " + loop + ", Swap: " + swap);
            else BubbleSort(inputs, n - 1, ++loop, swap);
        }

2014/09/12 11:11

Straß Böhm Jäger

def f(x):
    swap = 0
    for loop in __import__('itertools').count(1):
        s = swap
        for i in range(len(x)-1):
            if x[i] > x[i+1]:
                swap += 1
                x[i], x[i+1] = x[i+1], x[i]
        if s == swap: return loop, swap

while __name__ == '__main__':
    n = int(input('>>>'))
    print((lambda x:f(x) if len(x) == n else 'Error')([*map(int, input('>>>>>>').split())]))

파이썬 3.5.1

2016/06/25 10:53

Flair Sizz

깔끔하네요^^ - 디디, 2016/10/20 12:13
//  go 1.7.5 로 작성했습니다.

package main 

import "fmt"

func main() {
    fmt.Println("input data:")
    var userInputLimit, userInput int
    var data []int
    fmt.Scan(&userInputLimit)

    for i := 0; i < userInputLimit; i++ {
        fmt.Scan(&userInput)
        data = append(data, userInput)
    }

    _, lastSwapCount, loopCount := bubbleSort(data)
    fmt.Println(loopCount, lastSwapCount)
}


func bubbleSort(data []int) ([]int, int, int) {
    var loopCount, swapCount, lastSwapCount int

    for swapCount = 1; swapCount > 0; loopCount++{
        swapCount = 0
        for i := 0; i < len(data) - 1; i++ {
            if data[i] > data[i+1] {
                data[i], data[i+1] = data[i+1], data[i]
                swapCount++
            }
        }
        lastSwapCount += swapCount
    }

    return data, lastSwapCount, loopCount
}

2017/03/30 20:22

Wizardeye

def bubble_sort(a):
        n_loop = 0
        n_swap = 0
        while True:
                i = 0
                n_loop += 1
                swap_hist = n_swap
                while i < len(a)-1:
                        if a[i] > a[i+1]:
                                tmp = a[i]
                                a[i] = a[i+1]
                                a[i+1] = tmp
                                n_swap += 1
                        i += 1
                if swap_hist == n_swap:
                        print n_loop, n_swap
                        return()

a = [3, 1, 4, 1, 5, 9, 2, 6]
bubble_sort(a)

2014/05/16 16:00

superarchi

public class BubbleSort {
    public static void main(String args[]) {
        int[] array = {3,1,4,1,5,9,2,6};
        bubbleSort(array, array.length);
    }

    public static void bubbleSort(int[] array, int n) {
        int temp = 0;
        int loopCount = 0;
        int swapCount = 0;
        List<Integer> list = new ArrayList<Integer>();

        for (int i = 0; i < array.length; i++) {
            for (int j = 1; j < (array.length - i); j++) {
                if (array[j - 1] > array[j]) {
                    temp = array[j - 1];
                    array[j - 1] = array[j];
                    array[j] = temp;
                    swapCount++;
                }else{
                    loopCount++;
                }
            }
        }

        for(int i=1; i<array.length; i++){
            list.add(array[i]);
        }

        System.out.print(loopCount + " " + swapCount);
    }
}

2014/06/16 15:35

전 수현

var loopCount = 0; // Loop 횟수
var swapCount = 0; // Swap 횟수
var length = 8; // 배열의 갯수
var array = [3, 1, 4, 1, 5, 9, 2, 6]; // 배열의 요소 값
var isSwap = false; // Swap 여부
do { 
    isSwap = false;
    for ( var i = 0; i < length; i++ ) {
        if  ( array[i] > array[i+1] ) {
            var temp = array[i];
            array[i] = array[i+1];
            array[i+1] = temp;
            swapCount ++;
            isSwap = true;
        }   
    }
    loopCount ++;
} while( isSwap === true ) 

console.log ( "Array: [" + array + "]");
console.log ( "loopCount: " + loopCount );
console.log ( "swapCount: " + swapCount );

2014/07/01 16:35

GILIM HONG


#python 3.2.5

def bubble_sort(array, length, loop_count=0, swap_count=0):
    L = length
    loop_count += 1
    tmp_swap_count = 0
    for i in range(L-1):
        if (array[i] > array[i+1]):
            array[i], array[i+1] = array[i+1], array[i]
            tmp_swap_count += 1
    if tmp_swap_count == 0:
        return loop_count, swap_count

    swap_count += tmp_swap_count
    return bubble_sort(array, length, loop_count, swap_count)

def solve(inputdata):
    inputdata = inputdata.strip()
    lines = inputdata.split('\n')
    lines[1] = lines[1].strip()

    length = int(lines[0])
    array = [int(c) for c in lines[1].split(' ')]

    return bubble_sort(array, length)

def main():

    prob = '''8
    3 1 4 1 5 9 2 6'''

    print(solve(prob))

2014/07/03 11:57

Mun Kyeongsam

n = int(raw_input())
lst = raw_input().split(' ')[:n]

acc_loop = 0 # 총반복수
acc_swap = 0 # 총바꿔치기수

while True:
    cnt_swap = 0 # 매반복문당 바꿔치기 수
    for i in range(len(lst)-1):
        if lst[i] > lst[i+1]:
            tmp = lst[i]
            lst[i] = lst[i+1]
            lst[i+1] = tmp
            cnt_swap += 1
    acc_loop += 1 # 반복문당 반복횟수증가
    if cnt_swap is 0: # 바꿀게없으면 종료
        break
    acc_swap += cnt_swap # 총바꿔치기수에 누적
print acc_loop,
print acc_swap

2014/07/26 06:20

황 성호


// C++
#include <stdlib.h>
#include <iostream>
using namespace std;

void bubbleSort(int arr[], int arr_size)
{
    int temp = 0, pass = 0, compare = 0, swap = 0;

    for (int i = 1; i < arr_size; i++)
    {
        pass++;
        for (int j = 0; j < arr_size - i; j++)
        {
            compare++;
            if (arr[j] > arr[j + 1])
            {               
                temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
                swap++;
            }
        }
    }
    cout << pass << "  " << swap << endl;
}

int main()
{
    int *arr,arr_size;

    cout << "input data:\n";
    cin >> arr_size;

    arr = (int *)malloc(sizeof(int)*arr_size);

    for (int i = 0; i < arr_size; i++)
    {
        cin >> arr[i];
    }

    bubbleSort(arr, arr_size);

    free(arr);

    return 0;
}

2014/08/20 02:10

임시 변수 없이 비트 연산으로 바로 스왑을 적용했습니다.

import java.util.Scanner;

public class Main {

    public static void main(String[] ar){
        int swap = 0, loop = 0;
        boolean flg = false;

        Scanner sc = new Scanner(System.in);

        int[] arr = new int[sc.nextInt()];

        for(int i = 0; i < arr.length; i++)
            arr[i] = sc.nextInt();
        do{
            flg = false;
            for(int i = 0; i < arr.length-1; i++){
                if(arr[i] > arr[i+1]){
                    arr[i] = arr[i]^arr[i+1];
                    arr[i+1] = arr[i+1]^arr[i];
                    arr[i] = arr[i]^arr[i+1];
                    swap++;     
                    flg = true;
                }
            }
            loop++;
        }while(flg);

        System.out.println(loop + " " + swap);
        for(int i = 0; i < arr.length; i++)
            System.out.print(arr[i]);
    }

}

2014/10/03 12:28

천재일우

a = [3, 1, 4, 1, 5, 9, 2, 6]
def bubble(a):
    ResultLoop=0
    ResultSwap=0
    while 1:
        temp=0
        ResultLoop+=1
        for i in range(len(a[:-1])):
            if a[i]>a[i+1]:
                a[i],a[i+1]=a[i+1],a[i]
                ResultSwap+=1
                temp+=1
        if temp==0:
            break

    return (ResultLoop,ResultSwap)

print(bubble(a))

python 3.4 기준..

2014/10/24 00:26

Lee SeungChan

import java.util.Arrays;

public class BubbleSortMain {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        bubbleSort(new int[] { 3, 1, 4, 1, 5, 9, 2, 6 });
    }

    private static void bubbleSort(int[] is) {
        // TODO Auto-generated method stub
        int length = is.length;
        int loopCnt = 0;
        int swapCnt = 0;
        for (int i = 0; i < length; i++) {
            for (int j = i; j < length; j++) {
                if (is[i] > is[j]) {
                    int tmp = is[j];
                    is[j] = is[i];
                    is[i] = tmp;
                    swapCnt++;
                } else {
                    loopCnt++;
                }
            }
        }

        System.out.println(Arrays.toString(is));
        System.out.println(loopCnt + "," + swapCnt);
    }

}

2014/11/17 12:18

김 연태

C++

입력값 받아들이는 부분은 생략하고, 대신 예제에 주어진 값으로 실행.

#include <iostream>

using namespace std;

const int dim = 8;
int data[dim] = {3,1,4,1,5,9,2,6};

int swapCount = 0;

void swap(int& a, int&b)
{
    int t = a;
    a = b;
    b = t;
    ++swapCount;
}

int main(void)
{
    int passCount=0;
    bool sorted = false;

    while (!sorted)
    {
        ++passCount;
        sorted = true;
        for (int i=0; i<dim-1; ++i)
        {
            if (data[i] > data[i+1])
            {
                sorted = false;
                swap(data[i], data[i+1]);
            }
        }
    }
    cout << passCount << " " << swapCount << endl;
    return 0;
}

2014/12/29 14:13

Bang Keugyeol

Perl

<>;$t=<>;$i=1;
@a=split(/ /,$t);chomp @a;
while($i>0){
    $i=0;
    $l++;
    for(1..$#a){
        if($a[$_-1]>$a[$_]){
            ($a[$_-1],$a[$_])=($a[$_],$a[$_-1]);
            $s++;
            $i++
        }
    }
}
print "$l $s";

첫 줄의 정보는 별 필요 없어서 버립니다. @array=<STDIN>과 같이 입력을 받는 경우 터미널 실행시 EOF 누르기 귀찮아서 따로 하나씩 받습니다.

2014/12/31 17:36

*IDLE*

루비입니다.

class BubbleSorter
  attr_reader :array, :loop_count, :swap_count
  def initialize(array)
    @array = array
    @loop_count = 0
    @swap_count = 0
  end

  def sort
    loop do
      @loop_count += 1
      count_cache = swap_count
      run_cycle
      break if count_cache == swap_count
    end
  end

  def to_s
    "#{loop_count} #{swap_count}"
  end

  private
  def run_cycle
    (@array.size - 1).times do |i|
      j = i + 1
      if @array[i] > @array[j]
        @swap_count += 1
        @array[i], @array[j] = @array[j], @array[i]
      end
    end
  end
end

a = [3, 1, 4, 1, 5, 9, 2, 6]
b = BubbleSorter.new(a)
b.sort
puts "Anwser: #{b}"

2015/01/14 11:01

Shim Won

JAVA로 한번 해봤습니다. 아직 코딩초보라 변수가 너무 난잡하네요 ㅠㅠ

import java.util.Scanner;

public class Test { 
    public static void main(String[] args) {    
        Scanner sc = new Scanner(System.in);
        System.out.println("Input Data: ");
        int i = sc.nextInt();
        int t, number, cnt = 0, cnt2 = 0, cnt3 = 0; // cnt2 = swap 횟수, cnt3 = loop 횟수
        int[] sort = new int[i];

        for(int j = 0; j<i; j++)
            sort[j] = sc.nextInt();
        while(true) {
        for(int j = 0; j<i-1; j++) {
            if(sort[j] > sort[j+1]) {
                t = sort[j];
                sort[j] = sort[j+1];
                sort[j+1] = t;
                cnt++;
                cnt2++;
            }
        }
        cnt3++;
        number = cnt;
        cnt = 0;
        if(number == 0)
            break;
        }
        System.out.println("answer: ");
        System.out.print(cnt3+", "+cnt2);
    }
}

2015/01/14 17:48

으 아악

coding by python beginner

len = 8; t0 = [3,1,4,1,5,9,2,6]
loopCnt = swapCnt = 0
isSwap = True

while True:
    if isSwap == False: break
    isSwap = False; loopCnt += 1    
    for i in range(len-1):
        if t0[i] > t0[i+1]:
            t0[i], t0[i+1] = t0[i+1], t0[i]
            swapCnt += 1
            isSwap = True
print(loopCnt, swapCnt)

2015/01/30 17:42

vegan

결과 깂이 위의 5 8 과는 다르죠? c 언어로 작성해 보았습니다. (8 3 1 4 1 5 9 2 6 을 입력했을때요.)

#include <stdio.h>

int main(void)
{
    int inputNum[100], i = 0, j = 0, k = 0, l = 0, m = 0, change1 = 0;

    printf("몇개의 수를 bubble sorting 할까요?");
    scanf("%d", &l);

    for(i = 0; i < l; i++)
    {
        printf("입력: ");
        scanf("%d", &inputNum[i]);
    }

    for(i = 0; i < l - 1; i++)
    {
        for(j = 0; j < l - 1; j++)
        {
            change1 = inputNum[j+1];
            if(inputNum[j+1] <= inputNum[j])
            {
                inputNum[j+1] = inputNum[j];
                inputNum[j] = change1;
                k++;
            }
        }
        j = 0;
    }   
    printf("%d %d", k, l);  

    return 0;
}

2015/04/01 13:11

전승빈

Javascript 입니다.

var bubbleSort = function(arr) {
    var tmp;
    for(var i=0;i<arr.length;i++) {
        for(var j=1;j<arr.length;j++) {
            if(arr[j-1]>arr[j]) {
                tmp = arr[j-1];
                arr[j-1] = arr[j]
                arr[j] = tmp;
            }
        }
    }
    return arr;
}
bubbleSort([5,1,7,2,6,10,3]);

2015/05/06 15:13

JakartaKim

#448.py

count=0
swap_num=0
n=8
inputs="3 1 4 1 5 9 2 6".split(" ")
t=1
while(t):
    count+=1
    t=0
    for x in range(n-1):

        if inputs[x]>inputs[x+1]:
            inputs[x],inputs[x+1]=inputs[x+1], inputs[x]
            swap_num+=1
            t=1

print count,swap_num,inputs

2015/05/13 16:21

심재용

    static void exce61()// Bubble Sort
    {
        InputStream is = System.in;
        Scanner scan = new Scanner(is);
        int n = scan.nextInt();
        String str = scan.nextLine();
        str = scan.nextLine();
        String[] strArr = str.split(" ");
        int[] arr = new int[strArr.length];
        int cnt = -1, loop = 0, swap = 0;

        for (int i = 0; i < arr.length; i++)
            arr[i] = Integer.parseInt(strArr[i]);

        while (cnt != 0)
        {
            cnt = 0;
            loop++;

            for (int i = 0; i < arr.length - 1; i++)
            {
                if (arr[i] > arr[i + 1])
                {
                    int temp = arr[i];
                    arr[i] = arr[i + 1];
                    arr[i + 1] = temp;
                    swap++;
                    cnt++;
                }
            }
        }

        System.out.printf("%d %d",loop,swap);
    }

2015/08/26 15:07

조서현


#include "stdafx.h"
#include "stdlib.h" 


int _tmain(int argc, _TCHAR* argv[])
{
    int Array_Size; 
    int Pass_Count=0;
    int Swap_Count=0;
    scanf("%d",&Array_Size); 
    int* Array=(int*)malloc(Array_Size*sizeof(int)); 

    for(int i=0; i<Array_Size; i++){
        scanf("%d",&Array[i]);
    }

    for(int i=0; i<Array_Size-1; i++){
        Pass_Count++; 
        for(int j=0; j<Array_Size-1-i; j++){
            if(Array[i]>Array[i+1]){ 
                Swap_Count++;
                int temp=Array[i];
                Array[i]=Array[i+1]; 
                Array[i+1]=temp; 
            }
        }
    }
    printf("%d %d",Pass_Count,Swap_Count);
    free(Array); 
    return 0;
}

C언어

2015/10/11 01:40

Kicia Park

a = [3,1,4,1,5,9,2,6]

loop = 0
swap = 0
dec_end = 0

while True:
    loop += 1
    for i in range(len(a)-1):
        if a[i] > a[i+1]:
            a[i], a[i+1] = a[i+1], a[i]
            swap += 1
            dec_end = 1
    if not dec_end:
        break
    else:
        dec_end = 0

print('Total loop: %d번,  Swap: %d번' % (loop, swap))

2016/01/01 21:48

SPJung

  • python으로 작성하였습니다.
a = [3, 1, 4, 1, 5, 9, 2, 6]

swap=0
loop=0

for j in range(len(a)-1,0,-1):
    loop+=1
    oldSwap=swap
    for i in range(j):
        if a[i]>a[i+1]:
            swap+=1
            a[i],a[i+1]=a[i+1],a[i]
    if oldSwap==swap:
        break;


print loop,swap

2016/01/08 13:37

씨니컬우기님

list_size = input()
l = map(int,raw_input().split())

def bubble_sort(l):
    swap_times=0
    loop_times=0
    while 1:
        swapped=False
        loop_times+=1
        for i in range(len(l)-1):
            if l[i] > l[i+1]:
                l[i],l[i+1]=l[i+1],l[i]
                swap_times+=1
                swapped=True
        if not swapped : break
    return loop_times,swap_times

print bubble_sort(l)

2016/01/28 13:20

상파

파이썬입니다.

n = int(input())
xs = [int(x) for x in input().split(' ')][:n]

def bSort(ns):
    swaps = 0
    loops = 0
    arr = ns[::]
    while True:
        loops += 1
        cs = 0
        for i in range(n-1):
            if arr[i] > arr[i+1]:
                arr[i], arr[i+1] = arr[i+1], arr[i]
                cs += 1
        if cs is 0:
            break
        swaps += cs
    return loops, swaps

print("{0} {1}".format(*bSort(xs)))

2016/03/15 17:49

룰루랄라

Ruby

swap = ->a,i,cnt=0 { (a[i],a[i+1]=a[i+1],a[i]; cnt+=1) if a[i]>a[i+1]; [cnt,a] }
stage = ->cnt,a { (0..a.size-2).each {|i| cnt,a=swap[a,i,cnt]}; [cnt,a] }
b_sort = ->arr { loops,swaps,cnt = 0,0,-1;
  (cnt,arr=stage[0,arr]; loops+=1; swaps+=cnt) until cnt==0; [loops,swaps] }

Test

expect(swap[[2,1,3],0]).to eq [1,[1,2,3]] # case : swap
expect(swap[[1,2,3],1]).to eq [0,[1,2,3]] # case : sorted
expect(stage[0,[2,1,5,4]]).to eq [2,[1,2,4,5]] # case : swap
expect(stage[0,[1,2,4,5]]).to eq [0,[1,2,4,5]] # case : sorted
expect(b_sort[[3,1,4,1,5,9,2,6]]).to eq [5,8]

2016/03/16 02:39

rk

loop count가 조금 헷갈리긴 하지만,, ```{.java}

public void bubbleSort(int[] array){
    int swap_count = 0, loop_count = 0 ;
    for(int i = 0  ; i < array.length -1 ;i++){

        for(int  j = 0 ; j < array.length - i - 1 ; j++){

            if(array[j] > array[j+1]) {
                System.out.print(" | (" + array[j] + ","+array[j+1]+")");

                swap(array, j, j + 1);
                swap_count++;
                System.out.println(" ==>  (" + array[j] +" "+ array[j+1]+")");

            }
            else{
                loop_count++;
            }

        }
    }
    System.out.println("look/swap => " + loop_count + "/"+ swap_count);
    print(array);
}


public void print(int[] array){
    for(int i = 0  ; i < array.length ;i++){
        System.out.print(array[i] + " ");

    }
    System.out.println();
}
public void swap(int[] array, int i, int j){
    int temp = array[i] ;
    array[i] = array[j] ;
    array[j] = temp;

}

```

2016/04/22 22:48

xeo

def bubsort(x):
    itr, jtr = 0, 0
    while True:
        for i in range(len(x)-1):
            if x[i] > x[i+1]:
                [x[i],x[i+1]] = x[i+1], x[i]
                itr += 1
        jtr += 1
        if all(x[i] <= x[i+1] for i in range(len(x)-1)) : break

    print(x)
    print(jtr, itr)


bubsort([3,1,4,1,5,9,2,6])

답은 4, 8이 나와야 하는 것 같습니다.

5가 나오는 분들의 코드를 확인해보니 4번째 loop에서 완성된 결과가 나왔음에도 한차례 다시 loop을 도는 모습을 보입니다. 혹 제가 문제를 잘못 이해했다면 말씀 부탁드립니다.

2016/06/28 01:30

Park Jay

배열이 완성됐는지 확인하는데 한번 더 루프를 돌아야 합니다. 그래서 5가 맞는 것 같아요. - messi, 2019/04/03 21:13
import java.util.Scanner;

public class test {

    public static void main(String[] argv) {

        Scanner sc = new Scanner(System.in);

        int roopCount = 0;
        int swapCount = 0;
        boolean isSwap = false;

        int n = sc.nextInt();
        int[] numList = new int[n];

        for(int i = 0; i < numList.length; i ++){
            numList[i] = sc.nextInt();
        }

        // 시작 시간
       long startTime = System.currentTimeMillis();

        while(true){
            isSwap = false;
            roopCount++;

            for(int i = 0; i < numList.length - 1; i++){
                if(numList[i] > numList[i+1]){
                    int temp = numList[i];
                    numList[i] = numList[i+1];
                    numList[i+1] = temp;

                    swapCount ++;
                    isSwap = true;
                }
            }

            if(!isSwap) break;
        }

        System.out.println("Roop Count : " + roopCount + " Swap Count : " + swapCount); 

        // 종료 시간
        long endTime = System.currentTimeMillis();

        // 시간 출력
        System.out.println("##  소요시간(초.0f) : " + ( endTime - startTime )/1000.0f +"초"); 

    }

}




2016/07/27 09:01

이 승준

public void BubbleSortLoopAndSwapCount(int[] input)
        {
            int OrderCnt = 0;
            int temp = 0;
            int LoopCnt = 1;
            int SwapCnt = 0;
            for (int i = 0; i < input.Length-1; i++)
            {
                temp = 0;
                if (input[i] > input[i + 1])
                {
                    temp = input[i];
                    input[i] = input[i + 1];
                    input[i + 1] = temp;
                    SwapCnt++;
                }
                else
                {
                    OrderCnt++;
                }
                if((i == input.Length-2) && (OrderCnt < input.Length - 2))
                {
                    i = 0;
                    LoopCnt++;
                    OrderCnt = 0;
                }
            }
            Console.WriteLine("{0} {1}", LoopCnt, SwapCnt);

        }

사소한 오류땜에 시간을 다 잡아먹었네;;

2016/08/31 22:55

이규민

파이썬3.5

def f(a):
    'loop, swap 횟수 리턴'

    do_loop = True
    swap = 0
    loop = 0

    while do_loop:
        loop += 1
        do_loop = False    # do_loop의 위치가 중요하다.
        for i in range(len(a)-1):
            if a[i] > a[i+1]:
                a[i], a[i+1] = a[i+1], a[i]
                swap += 1
                do_loop = True

    return loop, swap


input('input data:\n')
print('answer:\n{} {}'.format(*f(list(map(int, input().split())))))    # 언패킹에 주의

2016/10/20 12:06

디디

print('input data:')
n = int(input(":"))
d = input(":")
dlist = [int(x.strip()) for x in d.split(' ')][0:n]
count = 0
swapcount = 0
while True:
    swap = False    
    for i in range(0, len(dlist) - 1):
        if not(dlist[i] <= dlist[i + 1]):
            dlist[i], dlist[i + 1] = dlist[i + 1], dlist[i]
            swap=True
            swapcount+=1
    count+=1
    if not swap:
        break
print('answer:')
print(count, swapcount)

Python 3.5.2에서 작성하였습니다.

2016/11/25 16:12

Yeo HyungGoo

def bubble_sort(a):
    swap = 0
    swap_list=[0]
    while True:
        for i in range(len(a)-1):
            if a[i] > a[i+1]:
                temp = a[i]
                a[i] = a[i+1]
                a[i+1] = temp
                swap += 1
        swap_list.append(swap)

        if swap_list[len(swap_list)-2] == swap_list[len(swap_list)-1]:
            print (swap_list[len(swap_list)-2], len(swap_list)-1)
            return ()
            break

a = [3, 1, 4, 1, 5, 9, 2, 6]
bubble_sort(a)

2016/12/15 02:39

Kim Da Seul

Haskell에서 Mutable array(STArray)를 이용하여 버블소트 구현해봤습니다. Haskell에서 Imperative programming을 하기는 정말 어렵네요 ㅎ

import Data.STRef (newSTRef, readSTRef, writeSTRef, modifySTRef)
import Data.Array.MArray (newListArray, readArray, writeArray, getBounds)
import Control.Monad (forM_, when)
import Control.Monad.ST (runST)
import GHC.Arr (unsafeFreezeSTArray)

whileM_ p f = go where go = p >>= \x -> when x (f >> go)

bubbleSort as = runST $ do
  arr <- newListArray (1, length as) as
  (l, h) <- getBounds arr
  swapped <- newSTRef True
  loopCount <- newSTRef 0
  swapCount <- newSTRef 0
  newH <- newSTRef h
  whileM_ (readSTRef swapped) $ do
    modifySTRef loopCount (+1)
    writeSTRef swapped False
    h <- readSTRef newH
    forM_ [l .. h-1] $ \i -> do
      a <- readArray arr i
      b <- readArray arr (i+1)
      when (a > b) $ do
        writeSTRef swapped True
        modifySTRef swapCount (+1)
        writeArray arr i b
        writeArray arr (i+1) a
        writeSTRef newH i
  unsafeFreezeSTArray arr
  loop <- readSTRef loopCount
  swap <- readSTRef swapCount
  return (loop, swap)

main :: IO ()
main = do
  let (loop, swap) = bubbleSort [3, 1, 4, 1, 5, 9, 2, 6]
  putStrLn $ show loop ++ " " ++ show swap

2016/12/16 01:08

Han Jooyung

def bubble_sort(loop,swap,a):
    switch = False
    for x in range(len(a)-1):
        if a[x] > a[x+1]:
            swap += 1
            switch = True
            a.insert(x+1,a.pop(x))
    if switch:
        return bubble_sort(loop+1,swap,a)
    else:
        return loop,swap

print(bubble_sort(1,0,[3,1,4,1,5,9,2,6]))

#### 2016.12.30 D-419 ####

2016/12/30 23:22

GunBang

입력받아 가공하는게 더 기네요 ^^;; 재귀호출을 통해 카운트를 늘리는 방식입니다.

package sort;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class BubbleSortRealization {
    private int[] inputList;
    public int swapCount = 0;
    public int loopCount = 0;
    private int arraySize = 0;
    private BufferedReader input;

    public BubbleSortRealization() {
    }

    public void printResult(){
        input = new BufferedReader(new InputStreamReader(System.in));
        arraySize = 0;
        try {
            arraySize = Integer.parseInt(input.readLine());
            this.inputList = new int[arraySize];
            String[] inputLine = input.readLine().split(" ");
            for(int i=0; i<arraySize; i++){
                this.inputList[i] = Integer.parseInt(inputLine[i]);
            }

            loopCount = mBubleSortWithCount(this.inputList);
            System.out.println(loopCount + " " + swapCount);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private int mBubleSortWithCount(int[] mArray) {
        int index = 0;
        int temp;
        boolean isSorted = true;

        while(index < arraySize-1){
            if(mArray[index] > mArray[index+1]){
                ++swapCount;
                temp = mArray[index];
                mArray[index] = mArray[index+1];
                mArray[index+1] = temp;
                isSorted = false;
            }
            index++;
        }

        if(!isSorted){
            return mBubleSortWithCount(mArray) + 1;
        }else{
            return 1;
        }
    }
}

2017/01/09 17:41

한인규(Hayden)

#include <stdio.h>
#include <stdlib.h>
void sort(int* arr);
int size;
int swap = 0;
int loop = 1;
void main() {
    size = 8;
    int arr[] = {3, 1, 4, 1, 5, 9, 2, 6};
    sort(arr);

    printf("\n%d %d", loop, swap);
}

void sort(int* arr) {
    int c = 0;
    for(int j=0;j<size;j++) {
        c = 0;
        for(int i=0;i<size;i++) {
            if(i+1 < size && arr[i] > arr[i+1]) {
                int temp = arr[i];
                arr[i] = arr[i+1];
                arr[i+1] = temp;
                swap++;
                c=1;
            }
        }
        if(c==0)
            break;
        loop++;
    }
}

2017/02/01 16:28

코딩초보

def bubble_sort(data):
    n, data=data
    N1, N2=1,0
    while sum(1 for i in range(0,n-1) if data[i]>data[i+1])>0:
        for i in  range(0,n-1):
            if data[i]>data[i+1]:
                data[i:i+2]= [data[i+1], data[i]]
                N2+=1
        N1+=1
    print(N1, N2)
bubble_sort([8,[3,1,4,1,5,9,2,6]])    

2017/02/19 20:51

김구경

import java.util.Scanner;

import static java.lang.System.in;

public class BubbleSort {

    public static void main(String[] args) {
        Scanner sc = new Scanner(in);
        int n = sc.nextInt();
        int[] a = new int[n];

        for (int i = 0; i < n; i++) a[i] = sc.nextInt();

        int swap = 0, loop = 0;

        for (int i = 0; i < n - 1; i++) {
            int count = swap;
            for (int j = 0; j < n - 1; j++) {
                if (a[j] > a[j + 1]) {
                    int t = a[j + 1];
                    a[j + 1] = a[j];
                    a[j] = t;
                    swap = swap + 1;
                }
            }
            loop = loop + 1;
            if (count == swap) break;
        }

        System.out.println(loop + " " + swap);
    }
}

2017/03/15 01:00

genius.choi

array = [int(x) for x in input("Input data:").split(" ")]
num_array = len(array)
sorted_array = sorted(array)
swap = 0
loop = 0

while sorted_array != array:
    for ind in range(num_array - 1):
        if array[ind] > array[ind + 1]:
            t = array[ind]
            array[ind] = array[ind + 1]
            array[ind + 1] = t
            swap += 1
            print("Swap", array)
    loop += 1
    print("Loop", array)

2017/05/24 11:23

Taewon Song

#include<stdio.h>
#include<stdlib.h>
int main(void)
{
    int size, i, j, save, loop, swap= 0;
    printf("배열의 크기는? ");
        scanf("%d",&size);
    int *arr = (int *)malloc(sizeof(int)*size);
    for(i = 0;i < size ; i++)
    {
        printf("%d번째 요소 : ",i+1);
        scanf("%d",&j);
        arr[i] = j;
        j = 0;
    }
    i = 0;
    for(i = 0; i < size; i ++)
    {
        for(j = 0; j < size-1; j++)
        {
            if(arr[j] > arr[j+1])
            {
                save = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = save;
            }
        }
    }
        for(i = 0; i < size; i ++)
    {
        print("%d\n ",arr[i]);
    }
}

2017/05/29 21:02

S ReolSt

python 3.4 재귀함수호출

def bubble(loop,cnt,src):
    c = 0
    for i in range(1, len(src)):
        if src[i-1] > src[i]:
            src[i-1], src[i] = src[i], src[i-1]
            c += 1
    if c == 0:
        return (loop, cnt)
    else:
        return bubble(loop+1, cnt+c, src)


s = list(map(int, input("input data: ").split()))
print("%d\n%s" % (len(s), ' '.join(map(str,s))))

print("answer:\n%d %d" % bubble(1,0,s))

2017/06/01 04:55

예강효빠

javascript

var input = 
`8
3 1 4 1 5 9 2 6`;

var lines = input.split("\n");
var size = parseInt(lines[0]);
var data = lines[1].split(" ").map(v => parseInt(v));

var loop = 0;
var swap = 0;
do {
    var swapped = false;
    for (let i = 0; i < size - 1; i++) {
        if (data[i] > data[i + 1]) {
            [data[i], data[i + 1], swap, swapped] = [data[i + 1], data[i], swap + 1, true];
        }
    }
    loop++;
} while (swapped);

console.log(`${loop} ${swap}`);

2017/06/20 09:44

funnystyle

파이썬을 배우는 초보자 입니다.

def sorting(getValue):
    running = True
    accum_swap = 0
    count_swap = 0

    while running :
        swaping = 0
        for i in range(len(getValue)-1):
            if getValue[i] > getValue[i+1]:
                getValue[i],getValue[i+1] = getValue[i+1],getValue[i]
                swaping += 1
        accum_swap += swaping
        count_swap += 1

        if swaping == 0:
            running = False

    print(count_swap)
    print(accum_swap)
    print(getValue)


value = int(input("숫자를 넣의세요 : "))
getValue = []
for i in range((value)):
    getValue.append(int(input()))

sorting(getValue)

2017/07/25 22:40

semipooh

C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char* argv[])
{
    int* arr = (int*)malloc(sizeof(int)*(argc-2));
    int flag = 1;
    int swapcount = 0;
    int loopcount = 0 ;
    for(int i=0;i<argc-2;i++)
    {
        arr[i] = atoi(argv[i+2]);   
        printf("%d ",arr[i]);
    }
    printf("\n");
    while(flag == 1)
    {
        for(int i=0;i<argc-3;i++)
        {
            int tmp = 0;
            if(arr[i]>arr[i+1])
            {
                tmp = arr[i];
                arr[i] = arr[i+1];
                arr[i+1] = tmp;
                swapcount++;
            }

        }
        flag = 0;
        for(int j=0;j<argc-3;j++)
        {
            if(arr[j]>arr[j+1])
            {
                flag = 1;
                break;
            }
        }
        loopcount++;
        //test
        for(int j=0;j<argc-2;j++)
        {
            printf("%d ",arr[j]);
        }

        printf("\n");   
    }
    printf("swap : %d , loopcount : %d\n",swapcount,loopcount);

    return 0;
}

2017/08/11 16:27

임꺽정

import java.util.Scanner;

class bubbleSorter {
    private int loops, swaps;

    public void printStat() { 
        System.out.println(loops + " " + swaps); 
    }

    public bubbleSorter(int[] arr) {
        loops = swaps = 0;      
        for (int last = arr.length - 2; last >= 0; last--) {
            boolean chagned = false;
            loops++;            
            for (int i = 0; i <= last; i++) {
                if (arr[i] > arr[i + 1]) {
                    int tmp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = tmp;                    
                    swaps++;
                    chagned = true;
                }               
            }
            if (!chagned)
                break;
        }

    }
}

public class test {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        int[] arr = new int[N]; 
        for (int i = 0; i < N; i++)
            arr[i] = sc.nextInt();

        new bubbleSorter(arr).printStat();
    }
}

2017/08/23 19:51

Noname

arr1 = [3,1,4,1,5,9,2,6]
loop_cnt = 0
swap_cnt = 0
while True:
    loop_cnt += 1
    swap_cnt_tmp = 0
    for i1 in range(1, len(arr1)):
        if arr1[i1-1] > arr1[i1]:
            swap_cnt_tmp +=1
            arr1[i1], arr1[i1-1] = arr1[i1-1], arr1[i1]
    swap_cnt += swap_cnt_tmp
    if swap_cnt_tmp == 0:
        break
print(loop_cnt, swap_cnt, arr1)

2017/08/29 10:44

piko

public class Test {

    public static void main(String[] args) {
        int[] arr = new int[] { 3, 1, 4, 1, 5, 9, 2, 6 };

        int swap = 0;
        int loop = 0;
        for (int i = 0; i < arr.length; i++) {
            for (int j = 1; j < arr.length - i; j++) {

                if (arr[j - 1] > arr[j]) {
                    int temp = arr[j - 1];
                    arr[j - 1] = arr[j];
                    arr[j] = temp;

                    swap++;
                } else {
                    loop++;
                }
            }
        }

        System.out.println(loop + " " + swap);
    }
}

2017/08/30 14:56

흑돼지

num=int(input())
nums=list(map(int, input().split()))

loop=0
swap=0
while True:
    count=0
    for i in range(num-1):
        if nums[i]>nums[i+1]:
            nums[i+1],nums[i]=nums[i],nums[i+1]
            count+=1
            print(nums)
    swap+=count
    loop+=1
    if not count: break

print(loop, swap)

2017/12/16 14:44

빗나감

파이썬 3.6

def BubbleSort(data):
    loop, swap, temp, chk = 0, 0, 0, 0
    while True:
        loop += 1
        for count in range(len(data)-1):
            if data[count+1] < data[count]:
                    swap += 1
                    temp = data[count]
                    data[count] = data[count+1]
                    data[count+1] = temp
                    chk = 1
        if not chk:
            break
        else:
            chk = 0
    print("answer:")
    print(loop, swap)

if __name__ == "__main__":
    m = int(input('요소의 개수를 입력하세요: '))
    data = [input('') for i in range(m)]
    print("inputdata:")
    print(m)
    print(' '.join(data),"\n")
    BubbleSort(data)

*결과값

요소의 개수를 입력하세요: 8
3
1
4
1
5
9
2
6
inputdata:
8
3 1 4 1 5 9 2 6 

answer:
5 8

2018/01/11 18:55

justbegin

size = raw_input("input data:\n")
a = [int(x) for x in raw_input().split()]

k = 1
total_loop = 0
total_swap = 0
while k != 0:
    k = 0
    for i in range(0,len(a)-1):
        if a[i] > a[i+1]: 
            t = a[i]
            a[i] = a[i+1]
            a[i+1] = t
            k=k+1
            total_swap = total_swap + 1
    total_loop = total_loop + 1
print ("answer:")
print total_loop, total_swap
print a

2018/01/15 04:01

영이

자바...

    static int[] a = { 3, 1, 4, 1, 5, 9, 2, 6 };
    static int loopCnt = 0, swapCnt = 0;

    public static void main(String[] args) {

        System.out.println(Arrays.toString(bubble(a)));
        System.out.println("Loop Count: " + loopCnt);
        System.out.println("Swap Count: " + swapCnt);
    }

    public static int[] bubble(int[] arr) {
        int tmp = 0;

        for (int i = 0; i < arr.length - 1; i++) {

            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    tmp = arr[j + 1];
                    arr[j + 1] = arr[j];
                    arr[j] = tmp;
                    swapCnt++;
                }
            }
            loopCnt++;
        }
        return arr;
    }

2018/01/17 15:26

강승규

# 파이썬

input_data = [8, [3, 1, 4, 1, 5, 9, 2, 6]]


def bubble_sort(i1, l1, swap=0, loop=0):
    swap_in_loop = 0
    for m in range(i1-1):
        if l1[m] > l1[m+1]:
            l1[m], l1[m+1] = l1[m+1], l1[m]
            swap +=1
            swap_in_loop += 1
    loop += 1
    if swap_in_loop == 0:
        return loop, swap
    else:
        return bubble_sort(i1, l1, swap, loop)


print(bubble_sort(input_data[0], input_data[1]))

2018/01/29 23:55

olclocr

def bubble(a):
    i = 0
    j = 0
    while 1:
        i += 1
        b = [a[i] <= a[i + 1] for i in range(len(a) - 1)]
        if all(b) == True:
            return i, j
        for k in range(len(a)-1):
            if a[k] > a[k+1]:
                j += 1
                (a[k], a[k+1]) = (a[k+1], a[k])

n = int(input())
b = [int(input()) for i in range(n)]
print(bubble(b))

2018/02/12 15:53

김동하

N=int(input("배열요소의 갯수를 입력하세요:"))
num_str=input("배열요소를 입력하세요:")
for_num_list=num_str.split(" ")
num_list=[]
for num in for_num_list:
    num_list.append(int(num))





flag=1
all_counter=0
loop_counter=0
while flag:
    counter=0
    for k in range(len(num_list)-1):
        if num_list[k]>num_list[k+1]:
            nTemp=num_list[k]
            num_list[k]=num_list[k+1]
            num_list[k+1]=nTemp
            counter+=1
    all_counter+=counter
    loop_counter+=1
    if counter==0:
        flag=0

print("%d %d"%(loop_counter,all_counter))




2018/02/20 09:31

D B

파이썬 3.6.4

def sort(n, num_list, count = 0, pass_num = 0) :

    count_2 = 0

    for i in range(0, n-1) :
        if num_list[i] <= num_list[i+1] :
            continue
        t = num_list[i]
        num_list[i] = num_list[i+1]
        num_list[i+1] = t
        count += 1
        count_2 += 1
    if count_2 == 0 :
        pass_num += 1
        print(num_list, pass_num, count)
    else :
        pass_num += 1
        return sort(n, num_list, count, pass_num)

재귀함수를 활용했습니다.

2018/03/20 20:47

박강민

파이썬 3 입니다.

def bubble():
    n = int(input('배열의 길이를 입력하세요 :'))
    data = list(map(int, input('배열을 입력하세요(띄어쓰기로 구분) :').split()))
    if len(data) != n: return '배열의 길이가 다릅니다.'
    swap, loop = 0, 0
    while True:
        count = 0
        for i in range(len(data)-1):
            if data[i] > data[i+1]:
                data[i], data[i+1] = data[i+1], data[i]
                swap += 1
                count += 1
        loop += 1
        if not count: break
    return '정렬 결과 : {}\n     loop : {}\n     swap : {}'.format(str(data)[1:-1], loop, swap)


print(bubble())

2018/05/12 14:46

Hyuk

#include<iostream>
using namespace std;
int arr_size()
{
    int size = 0;
    cout << "input data>> ";
    cin >> size;

    return size;
}
void swap_arr()
{
    int size = arr_size();
    int *p = new int[size];
    int tmp, loop_count = 0, swap_count = 0;

    for (int i = 0; i < size; i++)
    {
        cin >> p[i];
    }
    for (int i = 0; i < size; i++)
    {
        loop_count++;
        for (int j = i + 1; j < size; j++)
        {
            if (p[i] > p[j])
            {
                tmp = p[i];
                p[i] = p[j];
                p[j] = tmp;
                swap_count++;
            }
        }
    }

    cout << "Loop 횟수는 >> " << loop_count << " Swap 발생횟수는 >> " << swap_count << endl;
}

int main()
{
    swap_arr();
}

2018/05/26 00:22

Jun ki Kim

Swift 입니다.

func bubbleSort(_ givenItems: [Int]) {
    var items = givenItems, count = items.count, swapCount = 0, loopCount = 0

    for loopIndex in 0..<givenItems.count {
        var swapped = false
        for index in 0..<(count - loopIndex - 1) {
            if items[index] > items[index+1] {
                items.swapAt(index, index+1)
                swapped = true
                swapCount += 1
            }
        }
        loopCount += 1
        if swapped == false {
            break
        }
    }

    print("Loop count \(loopCount), Swap count \(swapCount)")
    print(items)
}

bubbleSort([3,1,4,1,5,9,2,6])

2018/05/31 23:44

졸린하마

Python

a = [3, 1, 4, 1, 5, 9, 2, 6]
for i in range(len(a)):
    for j in range(len(a)-1):
        if a[j] > a[j+1]:
            a[j], a[j+1] = a[j+1], a[j]
print(a)

2018/06/07 15:30

Taesoo Kim

a = [3, 1, 4, 1, 5, 9, 2, 6]
for i in range(len(a)-1):
    for j in range(len(a)-i-1):
        if a[j] > a[j + 1]:
            a[j], a[j + 1] = a[j + 1], a[j]
print(a)

2018/07/02 16:29

Jung Nill

def bubble_sort(loop,swap,a):
    switch = False
    for x in range(len(a)-1):
        if a[x] > a[x+1]:
            swap += 1
            switch = True
            a.insert(x+1,a.pop(x))
    if switch:
        return bubble_sort(loop+1,swap,a)
    else:
        return loop,swap

print(bubble_sort(1,0,[3,1,4,1,5,9,2,6]))

2018/07/09 15:54

다정

n = int(input())
sl = []
while 1:
    sl = list(map(int,input().split()))
    if len(sl) == n: break
    else: print('배열의 개수가 틀립니다. 재입력 하세요.')

swapcount, old, loopcount = 0,-1,0
while old < swapcount:
    old = swapcount
    for i in range(n-1):
        if sl[i] > sl[i+1]:
            sl[i], sl[i+1] = sl[i+1], sl[i]
            swapcount += 1
    loopcount += 1

print(loopcount, swapcount)

2018/07/10 23:08

Creator

namespace Bubble
{
    public static class Sort
    {
        public static int n = 0;
        public static int nLoop = 0;

        public static void BSort(int[] mArray)
        {
            for (int i = 0; i < mArray.Length - 1 ; i++)
            {
                for (int j = 0; j < mArray.Length - 1; j++)
                {
                    if(mArray[j] > mArray[j+1])
                    {
                        var temp = mArray[j + 1];
                        mArray[j + 1] = mArray[j];
                        mArray[j] = temp;
                        n++;
                    }

                    if (n == nLoop) 
                        nLoop = 0;

                    nLoop++;
                }
            }
            Console.WriteLine(String.Format("{0}\n{1}", nLoop, n));
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            int[] arr = { 3, 1, 4, 1, 5, 9, 2, 6 };

            Sort.BSort(arr);
            for (int i = 0; i < arr.Length; i++)
            {
                Console.Write(arr[i] + " ");
            }
        }
    }
}

2018/08/03 03:04

정태식

a = [*map(int,input('input date:').split())]
n = len(a)
print(a)
tot_s = 0
tot_loop = 0
l = 0
while l < n:
    k = 0
    s = 0
    for i in range(n-1):
        if a[i] > a[i+1]:
            a[i], a[i+1] = a[i+1], a[i]   
            s += 1
    tot_loop += 1              
    if s > 0:     
        tot_s += s   
    else:
        break     
    l += 1

print(a) 
print(tot_loop) 
print(tot_s)

2018/11/23 15:39

Dae Su Jeong

def bubble_sort(will_sort):
    result = will_sort[:]
    swap = 0
    allfind = 0
    fin = ''
    while not fin:
        for sorting in range(len(result) - 1):
            if result[sorting] > result[sorting + 1]:
                result[sorting], result[sorting + 1] = result[sorting + 1], result[sorting]
                fin = False
                swap += 1
        allfind += 1
        if fin == '':
            break
        else:
            fin = ''
    return [allfind, swap]
print(bubble_sort([3, 1, 4, 1, 5, 9, 2, 6]))

파이썬 3.6

2018/12/26 01:39

myyh2357

import java.util.Scanner;


public class KimSanghyeop {

    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        System.out.println("데이터를 입력하세요");

        String[] str_arr=sc.nextLine().split(" ");
        int[] int_arr = new int[str_arr.length];

        for(int f1=0;f1<str_arr.length;f1++)
        {
            int_arr[f1] = Integer.valueOf(str_arr[f1]);
        }

        int num_loop=0,num_swap=0;

        boolean loop= true;

        int temp;
        while(loop)
        {
            num_loop+=1;
            loop=false;
            for(int f1=0;f1<int_arr.length-1;f1++)
            {
                if(int_arr[f1] > int_arr[f1+1])
                {
                    loop=true;
                    num_swap+=1;
                    temp = int_arr[f1];
                    int_arr[f1] = int_arr[f1+1];
                    int_arr[f1+1] = temp;

                }
            }
        }
        System.out.println("루프 횟수 : "+num_loop);
        System.out.println("Swap횟수: "+num_swap);

    }
}

2019/01/03 21:44

김상협

C#

using System;
using System.Collections.Generic;
using System.Linq;

namespace CD061
{
    class Program
    {
        static void Main()
        {
            int arraySize = int.Parse(Console.ReadLine());
            int[] inputArray = new int[arraySize];
            inputArray = Console.ReadLine().Split(' ').Select((s) => int.Parse(s)).ToArray();

            BubbleSort anInput = new BubbleSort(inputArray.ToList());

            List<int> result = anInput.GetBubbleSortedList(out int loopCount, out int swapCount);

            Console.WriteLine($"{loopCount} {swapCount}");
            Console.WriteLine(string.Join(" ", result));

            Console.ReadKey();
        }
    }

    class BubbleSort
    {
        public List<int> SourceList = new List<int>();

        public List<int> BubbleSortedList = new List<int>();

        public BubbleSort(List<int> inputList)
        {
            SourceList = inputList;
            BubbleSortedList = inputList;
        }

        // 버블 정렬 실행
        public List<int> GetBubbleSortedList(out int loopCount, out int swapCount)
        {
            bool swapped = true; // 한 루프 내에서 swap이 발생하였는지 여부
            swapCount = 0;
            loopCount = 0;
            while (swapped)
            {
                swapped = false;
                for (int idx = 0; idx < SourceList.Count - 1; idx++)
                {
                    if (!IsSorted(idx))
                    {
                        Swap(idx);
                        swapped = true;
                        swapCount++;
                    }
                }
                loopCount++;
            }
            return BubbleSortedList;
        }

        // 특정 인덱스, 인덱스 + 1 관계가 정렬돼 있는지 확인
        private bool IsSorted(int idx)
            => BubbleSortedList[idx] <= BubbleSortedList[idx + 1] ? true : false;


        // 특정 인덱스, 인덱스 +1 의 값을 교환
        private void Swap(int idx)
        {
            int tmpVal = BubbleSortedList[idx];
            BubbleSortedList[idx] = BubbleSortedList[idx + 1];
            BubbleSortedList[idx + 1] = tmpVal;
        }
    }
}

2019/01/09 15:22

mohenjo

loop,swap = 1,0

def bubble(lis,le):
    global loop,swap
    if list(sorted(lis)) == lis:
        print(loop,swap)
        return
    else:
        for x in range(le-1):
            if lis[x] > lis[x+1]:
                lis[x],lis[x+1],swap = lis[x+1],lis[x],swap+1
    loop += 1
    bubble(lis,le-1)

2019/01/21 16:22

김영성

num = int(input())
arr = list(map(int, input().split()))
if len(arr) != num:
    raise Exception('Too Long')

def Bubble_sort(arr):
    loop_cnt = 0
    swap_cnt = 0
    no_swap_cnt = 0
    while True:
        for i in range(len(arr)-1):
            if arr[i] > arr[i+1]:
                temp = arr[i+1]
                arr[i+1] = arr[i]
                arr[i] = temp
                swap_cnt += 1
            else:
                no_swap_cnt += 1
        loop_cnt += 1
        if no_swap_cnt == len(arr) - 1:
            break
        else:
            no_swap_cnt = 0
    return (loop_cnt, swap_cnt)


print(Bubble_sort(arr))

2019/01/31 10:47

D.H.

def bubble_sort():
    num=int(input('배열의 개수를 정의하시오 : '))
    num_list=input('배열에 넣을 값을 쓰시오. 띄어쓰기로 구분 : ')
    num_list=num_list.split()
    cnt_a=0
    cnt_b=0
    for i in range (0, num-1):
        for j in range(0,num-1-i):
            cnt_a+=1
            if int(num_list[j])>=int(num_list[j+1]):
                cnt_b+=1
                num_list[j], num_list[j+1]=num_list[j+1],num_list[j]
    print(num_list)
    return cnt_a, cnt_b

2019/03/07 11:43

쨔이

package kr.koreait.interfaceTest;

import java.util.ArrayList;
import java.util.Scanner;

public class practice {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        System.out.print("배열의 개수를 입력하세요 : ");
        int n = sc.nextInt();
        ArrayList<Integer> array = new ArrayList<Integer>();
        sc.nextLine();
        for (int i = 0; i < n ; i++)
        {
            int a = sc.nextInt();
            array.add(a);
        }

        int cntArray = 0;
        int cntSwap = 0;
        int temp;
        while(true)
        {
            for (int i = 0; i < n; i++) {

                for (int j = 0; j < 4 - n; j++) {
                    if (array.get(j) > array.get(j+1)) {
                        temp = array.get(j);
                        array.set(j, array.get(j+1));
                        array.set(j+1, temp);
                        cntSwap++;
                    }
                }
                cntArray++;
            if (cntSwap ==0)
            {
                break;
            }
        }
            break;
        }
        System.out.println(cntArray + " " + cntSwap);
    }

}

2019/04/02 12:56

Albert

BubbleSort(L) : 리스트 L에 대해 한바퀴 정렬한후 Swap한 횟수를 반환하는 함수, makeSort(L) : 리스트 L이 정렬될 때까지 반복해서 BubbleSort하며 진행한 횟수와 Swap 횟수를 반환

def BubbleSort(L):
    k = 0
    for i in range(len(L)-1):
        if L[i] > L[i+1]:
            t = L[i]
            L[i] = L[i+1]
            L[i+1] = t
            k += 1    
    return k

def makeSort(L):
    s = 0
    for i in range(len(L)):
        k = BubbleSort(L)
        s += k
        if k == 0:
            print(i+1, s)

makeSort([3, 1, 4, 1, 5, 9, 2, 6])

2019/04/03 21:06

messi

def Bubble(sL,kaisu,sf):
    if len(sL)==1:
        kaisu+=1
        return "{} {}".format(kaisu,sf)

    for i in range(len(sL)):
        if sL[i]==min(sL):
            if i==0:
                break
            else:
                kaisu+=1;sf+=i;break
    sL.remove(min(sL))
    return Bubble(sL,kaisu,sf)

n=int(input("input data:\n"));inp=list(map(int,input().split()))
print(Bubble(inp,0,0))

이번에는 재귀함수를 썼으면서도 오류가 뜨지 않았던 매우 드문 경우였읍니다. 다만, 크기순으로 정렬한 수열을 굳이 얻을 필요없이 횟수만 세어주면 되므로, 배열의 가장작은 요소의 인덱스값을 리용하여 문제를 풀어나갔읍니다. 점점 재귀함수에 익숙해져 감을 느낍니다.^^

2019/05/05 14:16

암살자까마귀

def bubble_sort(a):
    loop_cnt = 0; swap_cnt = 0

    for i in range(len(a)):
        swap = 0
        for j in range(len(a)-1):
            if a[j] > a[j+1]:
                a[j], a[j+1] = a[j+1], a[j]
                swap_cnt += 1
                swap = 1
        loop_cnt += 1
        if not swap: break

    return loop_cnt, swap_cnt

2019/06/09 14:35

이진형

a=int(input("배열의 원소 개수 입력: "))
n=input("배열입력: ").split(' ')
array=[]
swap=0
count=2
for i in n:
    array.append(int(i))
j=0
while sorted(array) !=array:
    if array[j]>array[j+1]:
        temp=array[j]
        array[j]=array[j+1]
        array[j+1]=temp
        swap +=1
    else:
        pass

    j +=1
    if j==len(array)-1:
        j=0
        count +=1

print("%d %d"%(count,swap)

2019/08/22 18:03

박재욱

a = [3, 1, 4, 1, 5, 9, 2, 6] count = 0 for i in range(len(a)): for j in range(i+1,len(a)): if a[i] > a[j]: a[i],a[j] = a[j],a[i] count += 1 else: continue print(a,count)

a = [3, 1, 4, 1, 5, 9, 2, 6]
count = 0
for i in range(len(a)):
    for j in range(i+1,len(a)):
        if a[i] > a[j]:
            a[i],a[j] = a[j],a[i]
            count += 1
        else:
            continue
print(a,count)

2019/09/25 11:23

황수빈

List = [3,1,4,1,5,9,2,6]
temp = 0
swap_count = 0
loop_count = 0
while True :
    loop_count += 1
    end_count = 0
    for i in range(len(List)-1) :
        if List[i] > List[i+1] :
            temp = List[i]
            List[i] = List[i+1]
            List[i+1] =temp
            swap_count += 1
            end_count += 1            
        else :
            continue
    if end_count ==0  :
        print (loop_count, swap_count)
        break

2019/11/04 23:11

semipooh

import java.util.*;
public class BubbleSort {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        int times = scan.nextInt();
        //int[] nums = Arrays.stream(str).mapToInt(Integer::parseInt).toArray();
        ArrayList<Integer> list = new ArrayList<Integer>();
        for(int i=0; i<times; i++) {
            list.add(scan.nextInt());
        }
        int loop = 0;
        int swap = 0;
        int check = 0;
        for(int s=0;;s++) {
        for(int i=0;;i++) {
            if(i>=list.size()-1) {
                loop++;
                for(int k=0; k<list.size()-1; k++) {
                    if(list.get(k)<=list.get(k+1)) {
                        check++;
                    }
                }
            if(check==list.size()-1) {
                loop++;
                break;
            }
            check=0;
            break;
            }
            if(list.get(i)>list.get(i+1)) {
                Collections.swap(list, i, i+1);
                swap++;
            }
        }
        if(check==list.size()-1) {
            break;
        }
        }
        System.out.println(loop+" "+swap);
    }
}

2019/11/23 18:48

big Ko

def bubble(data):
    loop = 0
    swap = 0
    sw = True
    while sw:
        loop += 1
        chk = 0
        for i in range(len(data)-1):
            if data[i] > data[i+1]:
                swap += 1
                data[i], data[i+1] = data[i+1], data[i]
                chk += 1
        if chk == 0:
            break

    return loop, swap

def main():
    a = [3, 1, 4, 1, 5, 9, 2, 6]
    print('input data: \n{}\n{}\n\nanswer: \n{}'.format(len(a), ' '.join(map(str, a)), bubble(a)))

if __name__ == '__main__':
    main()

2020/04/20 15:59

Hwaseong Nam

input data: 8 3 1 4 1 5 9 2 6 answer: (5, 8) Process finished with exit code 0 - Hwaseong Nam, 2020/04/20 15:59
def bubble_sort(l):
    loop_count = 0
    swap_count = 0
    while True:
        loop_count += 1
        prev_swap_count = swap_count
        for i in range(len(l) - 1):
            prev, curr = (l[i], l[i + 1])
            if prev > curr:
                swap_count += 1
                l[i], l[i + 1] = (curr, prev)
        if swap_count == prev_swap_count:
            break
    return (loop_count, swap_count)

2020/05/10 01:56

김준혁

s
N = list(input())
swap = 0
loop = 0
for i in range(1,len(N)):
    inswap = 0
    for j in range(0,i):
        if N[i] < N[j]:
            N[i],N[j] = N[j],N[i]
            swap += 1
            inswap += 1
        else:
            continue
    if inswap == 0:
        loop +=1


print(loop,swap)

문제의 loop뜻을 모르겠어서 한번의 swap도 없이 배열을 지나갔을 떄 loop += 1을 하였습니다....

2020/05/13 00:28

Money_Coding

def bubbleSort(s):
    result = s
    loopCount = 0
    swapCount = 0
    while 1:
        jud = []
        for i in range(0, len(result) - 1):
            if not (result[i] <= result[i + 1]):
                temp = result[i]
                result[i] = result[i + 1]
                result[i + 1] = temp
                swapCount += 1
                jud += "F"
            else:
                jud += "T"
        if "F" not in jud:
            break
        loopCount += 1
    print(loopCount, swapCount)


bubbleSort([3, 1, 4, 1, 5, 9, 2, 6])

2020/11/25 15:27

김우석

def bubble_sort(lists):

  total_count=0

  boool=True

  j=0

  while boool==True:

    count=0

    for i in range(0,len(lists)-1,1):

      if lists[i]>lists[i+1]:

        lists[i],lists[i+1]=lists[i+1],lists[i]

        count+=1

    j+=1

    if count==0:

      boool=False

    total_count+=count

  return j,total_count

print(bubble_sort([3,1,4,1,5,9,2,6]))

2020/12/28 16:30

전준혁

def bubble(_input):
    temp = list(_input.split())
    count = 0
    loop_1 = 0
    while True:
        loop = 0
        for i in range(len(temp)):
            try:
                if temp[i] > temp[i+1]:
                    t = temp[i]
                    temp[i] = temp[i+1]
                    temp[i+1] = t
                    count += 1
                    loop += 1
            except: pass

        loop_1 += 1
        if loop == 0:
            break

    return print('answer: ', loop_1, count)

bubble(input("INPUT >> "))

2021/01/18 08:37

DSHIN

n = input('input data: '+ '\n')

while True:
    nums_input = input().split()
    if len(nums_input) == int(n[-1]):
        break

nums = list(map(int, nums_input))

def bubble_sort(a):
    swap, loop = 0, 0
    # a = [3, 1, 4, 1, 5, 9, 2, 6]

    while True:
        count = 0
        for i in range(len(a)-1):
            if a[i] <= a[i+1]:
                continue
            else:
                t = a[i]
                a[i] = a[i+1]
                a[i+1] = t
                count += 1
        loop += 1
        swap += count
        if count == 0:
            break
    return print('answer:', '\n', loop, ' ', swap, sep='')

bubble_sort(nums)

2021/02/13 12:16

Ha

swap = 0
loop = 0
a = [3, 1, 4, 1, 5, 9, 2, 6]
b=sorted(a)
while True:
    if a==b:
        loop+=1
        break
    else:
        for i in range(len(a)-1):
            if a[i]>a[i+1]:
                temp=a[i]
                a[i]=a[i+1]
                a[i+1]=temp
                swap+=1
        loop+=1

print(loop)
print(swap)
print(a)

2021/03/04 20:46

fox.j

l = [3,1,4,1,5,9,2,6]
loop,swap = 0,0

while 1:
    loop += 1
    loopout = []
    for i in range(len(l)-1):
        if l[i]>l[i+1]:
            l[i],l[i+1] = l[i+1],l[i]
            swap +=1
            loopout.append('N')
        else : loopout.append('Y')
    if 'N' not in loopout : break
print(loop,swap)

2021/05/28 10:47

약사의혼자말

def bubble(b):
    times = 0
    swap = 0
    while b != sorted(b):
        for i in range(len(b)-1):
            if b[i] > b[i+1]:
             b[i], b[i+1] = b[i+1], b[i]
             swap += 1
            else:
             times += 1
             i += 1
    return print(f"answer:\n {times} {swap}")

b = [3,1,4,1,5,9,2,6]
bubble(b)

2021/06/13 20:05

ss2663

#codingdojing_bubble sort
#가장 간단하게 생각할 수 있는건, N^2 만큼 for loop를 돌리는 것.
#참고한 풀이는 while로 대체해서 시간을 줄임.

def bubble_sort(a):

    swap_count = 0
    loop_count = 0
    swap = True

    while swap:
        swap = False                    #initializtion
        loop_count += 1

        for i in range(len(a)-1):       #loop start
            if a[i] > a[i+1]:
                a[i], a[i+1] = a[i+1], a[i]
                swap_count += 1
                swap = True

    print(loop_count, swap_count, a)

bubble_sort([3, 1, 4, 1, 5, 9, 2, 6])



2021/08/06 09:12

Jaeman Lee


n = int(input("배열의 원소의 개수는?"))
arr =[]
for j in range(n):
  arr.append(int(input("원소를 입력하시오")))  

def sort (a):
    swap_n = 0
    loop_n = 1
    while a!= sorted(a):
        for k in range(len(a)-1):
            if a[k]>a[k+1]:
                t=a[k]
                a[k]=a[k+1]
                a[k+1]=t
                swap_n += 1
        loop_n +=1
    return print(loop_n,swap_n)

sort(arr)


2021/12/29 01:58

양캠부부

_input = input("input data :")
_input = list(map(int,_input.split()))

_loop = 0
_swap = 0

while(True):
    _swap_plus = 0

    for i in range(0,len(_input)-1):
        if _input[i] > _input[i+1] :
            _input[i],_input[i+1] = _input[i+1],_input[i]
            _swap_plus += 1

    if _swap_plus == 0 : break

    _swap += _swap_plus
    _loop += 1

print("answer :",_loop,_swap)
print(_input)


2022/01/23 16:38

강태호

// Rust

fn bubble_sort(vec_: Vec) -> (usize, usize) {

let mut vec = vec_;
let mut n_loop = 0;
let mut n_swap = 0;
loop {
    n_loop += 1;
    let n_swap_prev = n_swap;
    for i in 0..vec.len()-1 {
        if vec[i] > vec[i+1] {
            vec.swap(i, i+1);
            n_swap += 1;
        }
    }
    if n_swap == n_swap_prev {
        break;
    }
}
(n_loop, n_swap)

}

[test]

fn test() {

assert_eq!(bubble_sort(vec![3,1,4,1,5,9,2,6]), (5, 8));

}

2022/01/27 19:22

JW KIM

def jud(a):
    return [(a[i+1]-a[i]) > -1 for i in range(len(a)-1)].count(False)

a = [3, 1, 4, 1, 5, 9, 2, 6]
print(' ',a)

loop, swap = 0 , 0

while jud(a) != 0:
    for i in range(len(a)-1):
        if a[i] > a[i+1]:
            a[i],a[i+1] = a[i+1],a[i]
            swap += 1
        print(a)    
    loop += 1 
    print(loop,a)
print(loop, swap)

2022/02/11 13:32

로만가

loop값을 못찾겠네요... ㅠㅠ

package org.javaturotials.ex;
import java.util.*;


public class test {
    public static void main(String[] args) {

    Scanner sc =new Scanner(System.in);
    int num =sc.nextInt();
    int[] arr = new int[num];
    int count=0;
    int swapc=0;
    for(int i=0; i<arr.length; i++) {
        arr[i] = sc.nextInt();
    }
    for(int i=0; i<arr.length; i++) {
    for(int j=0; j<i; j++) {
        if(i!=j) {
            if(arr[i]<arr[j]) {
                int t = arr[i];
                arr[i] =  arr[j];
                arr[j] = t;
                swapc++;
            }
        }
    }
    }
    System.out.println(swapc);
    }
    }

2022/02/18 17:29

Kkubuck

lena = int(input("input data:\n"))
a = [int(x) for x in input().split()]
Loop = 0
Swap = 0
noSwap = 0

while noSwap != (lena-1):
    noSwap = 0
    Loop += 1
    for i in range(lena-1):
        if a[i] > a[i+1]:
            a[i], a[i+1] = a[i+1], a[i]
            Swap += 1
        else:
            noSwap += 1

print('answer:')
print(Loop,Swap)

2022/06/21 14:39

김시영

import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        int size = 0;

        // ** Get size of array.
        while(true) {
            System.out.print("Enter size: ");
            size = scan.nextInt();

            if(size<=0)
                System.out.println("The size is less than zero.");
            else
                break;
        }

        // ** Create array & Get elements.
        int[] list = new int[size];
        System.out.print("Enter elements: ");
        for(int i=0; i<size; i++)
            list[i] = scan.nextInt();

        // ** Bubble sorting
        printArray(list, "Before sorting: ");
        bubbleSorting(list);
        printArray(list, "After sorting: ");
    }

    private static void printArray(int[] list, String contents) {
        System.out.printf(contents);
        for(int i=0; i<list.length; i++) {
            if(i==0)
                System.out.printf("{%d", list[i]);
            else
                System.out.printf(", %d", list[i]);
        }
        System.out.println("}");
    }

    private static void bubbleSorting(int[] list) {
        for(int end=list.length-1; end>0; end--)
            for(int start=0; start<end; start++)
                if(list[start]>list[start+1]) {
                    int tmp = list[start+1];
                    list[start+1] = list[start];
                    list[start] = tmp;
                }
    }
}

2022/10/02 02:51

유로

def swap(l,id1,id2):
    temp = l[id1]
    l[id1] = l[id2]
    l[id2] = temp

n = int(input())
data = input()
data = data.split()
data = [int(char) for char in data]

#data = [int(char) for char in input().split()]
#print("n: ",n)
#print("data: ",data)

finished = False
n_loop = 0
n_swap = 0
while finished == False:
    finished = True
    n_loop += 1
    for i in range(n-1):
        if data[i] > data[i+1]:
            finished = False
            swap(data,i,i+1)
            n_swap += 1
print("answer:")
print(n_loop,n_swap)

input으로 받았어요

2023/02/28 12:34

제작자

N = int(input('배열의 갯수 ?: '))
input_data = [int(x) for x in input("배열의 요소값? :").split()]

loop_su = 0
swap_su = 0
while True:
    swap=0
    loop_su += 1
    for i in range(N-1):
        if input_data[i] > input_data[i+1]:
            input_data[i], input_data[i+1] = input_data[i+1], input_data[i]
            swap += 1
    if swap == 0:
        print('배열을 따라 진행(Loop)한 횟수:' + str(loop_su) + ' Swap이 발생한 총 횟수:' + str(swap_su))
        break
    swap_su += swap

2023/12/14 19:19

insperChoi

목록으로