Sorting – Bubble sort
Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each pair of adjacent items and swaps them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm, which is a comparison sort, is named for the way smaller or larger elements "bubble" to the top of the list. Although the algorithm is simple, it is too slow and impractical for most problems even when compared to insertion sort. It can be practical if the input is usually in sorted order but may occasionally have some out-of-order elements nearly in position. #include <iostream> #include <stdio.h> #include <math.h> #include <conio.h> #include <stdlib.h> using namespace std; #define MAX 100 /////functie pt citirea datelor int read_data(int *a) { int i,n; printf("n=");scanf("%d",&n); for (i=0;i<n;i++) { printf("a[%d]=",i); scanf("%d",&a[i]); } return n; } ////////funtctie pt tiparirea elementelor din tablou void list(int *a,int n) { int i; for (i=0;i<n;i++) printf("%d",a[i]); printf("\n"); } void bubble(int *a ,int n) { int i;//variabila pt parcurgerea ciclarii int j; int aux;//variabila utilizata pt interschimbare for (i=0;i<n-1;i++) for (j=n-1;j>i;j--) if(a[j-1] > a[j]) { aux = a[j]; a[j]=a[j-1]; a[j-1] = aux; } } void main() { int i,n; int a[100]; n = read_data(a); bubble(a,n); list(a,n); }
32,201 total views, 1 views today