It is the simplest sorting technique with low memory consumption and low performance compared to other sorting techniques.
here we just compare adjacent elements and swap if there not in order.
after first iteration the last element is correctly placed. iterate the same until everything sorted.
####################################################
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 10
void bubbleSort(int * const data);
int main(int argc, char** argv) {
int data[SIZE];
int i;
srand(time(NULL));
for(i=0;i<SIZE;i++){
data[i]=rand()%100+1;
printf("%d\n",data[i]);
}
bubbleSort(data);
printf("\n\n\n");
for(i=0;i<SIZE;i++){
printf("%d\n",data[i]);
}
return (EXIT_SUCCESS);
}
void bubbleSort(int * const data){
void swap(int * const swap1,int * const swap2);
int i;
for(i=0;i<SIZE;i++){
int j;
for(j=0;j<SIZE-i-1;j++){
if(data[j]>data[j+1]){
swap(&data[j],&data[j+1]);
}
}
}
}
void swap(int * const swap1, int * const swap2){
int tmp=*swap1;
*swap1=*swap2;
*swap2=tmp;
}
here we just compare adjacent elements and swap if there not in order.
after first iteration the last element is correctly placed. iterate the same until everything sorted.
####################################################
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 10
void bubbleSort(int * const data);
int main(int argc, char** argv) {
int data[SIZE];
int i;
srand(time(NULL));
for(i=0;i<SIZE;i++){
data[i]=rand()%100+1;
printf("%d\n",data[i]);
}
bubbleSort(data);
printf("\n\n\n");
for(i=0;i<SIZE;i++){
printf("%d\n",data[i]);
}
return (EXIT_SUCCESS);
}
void bubbleSort(int * const data){
void swap(int * const swap1,int * const swap2);
int i;
for(i=0;i<SIZE;i++){
int j;
for(j=0;j<SIZE-i-1;j++){
if(data[j]>data[j+1]){
swap(&data[j],&data[j+1]);
}
}
}
}
void swap(int * const swap1, int * const swap2){
int tmp=*swap1;
*swap1=*swap2;
*swap2=tmp;
}
No comments:
Post a Comment