LoginSignup
0
2

More than 5 years have passed since last update.

バブルソート

Posted at

バブルソート…•配列の末尾から隣接する要素を順番に比べていき、大小関係が逆ならば交換する。
例53421
→15342
→12534
→12354
→12345


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

void BubbleSort();
void MakeArray();
void ShowData();
int main();


const int SIZE = 10;
int data[SIZE];

void MakeArray(){
    int i, num;
    srand((unsigned) time(NULL));

    for(i=0;i<SIZE;i++){
        num=rand()%900 + 100; //取得する値を100~999の間とする
        data[i] = num;
    }
}

void ShowData(){
    for(int i = 0; i < SIZE; i++){
        if(i != SIZE -1){
            printf("%d, ", data[i]);
        }else{
            printf("%d", data[i]);
        }
    }
    printf("\n");
}

void BubbleSort(){
    int cnt = SIZE - 1;
    int tmp;

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

        for(int j = cnt;i < j; j--){  

            if(data[j] < data[j-1]){
                tmp = data[j];
                data[j] = data[j-1];
                data[j-1] = tmp;
            }else{
                continue;
            }
        }
    ShowData();
    }
}

int main(){
    MakeArray();

    printf("(ソート前)\n");
    ShowData();

    BubbleSort();

    printf("(ソート後)\n");
    system("PAUSE");
    return 0;
}
0
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2