버블 정렬 (Bubble Sort)

2021. 1. 11. 14:05·Algorithm/Sorting algorithm
반응형

버블 정렬(Bubble Sort)은 서로 연접한 두 항으 계속해 비교하는 방식이다.

n번째 항이 있다고 가정할때

0번째 항과 1번째 항 비교, 1번 항 2번 항 비교, 2번 항 3번 항 비교해서 마지막 두항 n-1번 항 n 번항을 비교후 마지막 항의 정보가 결정된다.

 

 오름차순으로 정렬할 경우 가장 큰값을 먼저 결정하는 특징이 있다.

 

`3, 4 ,1 ,5 ,2` 를 버블정렬 해보겠다.

 

1단계

 

0번항 1번항 비교 (유지)

3 4 1 5 2

1번항과 2번항 비교 (교환)

3 1 4 5 2

2번항과 3번항 비교(유지)

3 1 4 5 2

3번항과 4번항 비교(교환)

3 1 4 2 5

1단계 완료

 

2단계

 

다시 0번항 1번항 비교 (교환)

3 1 4 2 5

1번항과 2번항 비교 (유지)

1 3 4 2 5

2번항과 3번항 비교 (교환)

1 3 4 2 5

3번항과 4번항 비교 (유지)

1 3 2 4 5

2단계 완료

 

이렇게 마지막 오름차순으로 정렬될때까지 반복시행한다.

 

더보기

소스코드

#include<stdio.h>

int main(void)
{
	int alist[5] = { 3,4,1,5,2 };
	int i = 0, j = 0, tmp = 0;

	for (i = 4; i > 0; i--)
		for (j = 0; j < i; j++)
			if (alist[j] > alist[j + 1])
			{
				tmp = alist[j];
				alist[j] = alist[j + 1];
				alist[j + 1] = tmp;
			}

	for (i = 0; i < 5; ++i)
		printf("%d\t", alist[i]);
	printf('\n');
	return 0;
}

Break point걸고 디버그모드로 하나씩 따라가면서 직접 바뀌는걸 보면 이해하기 쉬울것이다.

 

반응형

'Algorithm > Sorting algorithm' 카테고리의 다른 글

퀵 정렬 (Quick Sort)  (1) 2021.01.28
선택정렬 (Selection sort)  (0) 2021.01.11
'Algorithm/Sorting algorithm' 카테고리의 다른 글
  • 퀵 정렬 (Quick Sort)
  • 선택정렬 (Selection sort)
Penguin Dev
Penguin Dev
What does the Penguin say?
    글쓰기 관리
  • Penguin Dev
    Pengha!
    Penguin Dev
  • 전체
    오늘
    어제
    • 분류 전체보기 (152)
      • Java & Spring (5)
      • System Hacking (4)
      • Algorithm (8)
        • Sorting algorithm (3)
      • Python (6)
      • Web (2)
        • Web Hacking & Security (2)
      • Write-Up (108)
        • pwnable.kr (17)
        • HackCTF (16)
        • 해커스쿨 FTZ (21)
        • LOB(lord of bufferoverflow) (19)
        • LOS (lord of sql injection) (28)
        • XSS-game (6)
        • Webhacking.kr (1)
      • SUA (19)
        • 오픈소스 보안 (19)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    코드트리조별과제
    spring
    Lock
    putval()
    동시성처리
    ReentrantLock
    concurrenthashmap vs hashmap
    reentrantlock실습
    AQS
    LOB
    ConcurrentHashMap
    lord of bufferoverflow
    spring boot
    동시성
    enumerate #list comprehension
    tabat
    쿠폰발급
    Java
    thread-safe
    hashmap vs concurrenthashmap
    computeifabsent
    computeifabsent()
    computeifpresent
    sqlinjection
    nop sled
    DB정리
    CountDownLatch
    코드트리
    SpringBoot
    computeifpresent()
  • 최근 댓글

  • 반응형
  • hELLO· Designed By정상우.v4.10.3
Penguin Dev
버블 정렬 (Bubble Sort)
상단으로

티스토리툴바