mirror of
https://github.com/TheAlgorithms/C
synced 2024-11-22 05:21:49 +03:00
Change BubbleSort.c format
This commit is contained in:
parent
bc1c15e24f
commit
edf400739c
@ -1,40 +1,62 @@
|
||||
//sorting of linked list using selection sort
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
|
||||
int main(){
|
||||
|
||||
int* ARRAY=NULL;
|
||||
int ContinueFilling=1; //This is to know if we should continue filling our array
|
||||
int ARRAY_LENGTH=0,isSorted=0,i,TEMPORARY_ELEMENT;
|
||||
|
||||
//This code part is for filling our array
|
||||
while(ContinueFilling){
|
||||
printf("Enter the value number %d \n",ARRAY_LENGTH+1);
|
||||
ARRAY=(int *)realloc(ARRAY,sizeof(int)*(ARRAY_LENGTH));
|
||||
scanf("%d",&ARRAY[ARRAY_LENGTH]);
|
||||
ARRAY_LENGTH+=1;
|
||||
printf("would you enter an other value (1:Continue/0:Sort the actual array)?\n");
|
||||
scanf("%d",&ContinueFilling);
|
||||
/*Displays the array, passed to this method*/
|
||||
void display(int arr[], int n){
|
||||
|
||||
int i;
|
||||
for(i = 0; i < n; i++){
|
||||
printf("%d ", arr[i]);
|
||||
}
|
||||
|
||||
printf("\n");
|
||||
|
||||
}
|
||||
|
||||
//Then we sort it using Bubble Sort..
|
||||
/*Swap function to swap two values*/
|
||||
void swap(int *first, int *second){
|
||||
|
||||
int temp = *first;
|
||||
*first = *second;
|
||||
*second = temp;
|
||||
|
||||
}
|
||||
|
||||
while(!isSorted){ //While our array's not sorted
|
||||
isSorted=1; //we suppose that it's sorted
|
||||
for(i=0;i<ARRAY_LENGTH-1;i++){ //then for each element of the array
|
||||
if(ARRAY[i]>ARRAY[i+1]){ // if the two elements aren't sorted
|
||||
isSorted=0; //it means that the array is not sorted
|
||||
TEMPORARY_ELEMENT=ARRAY[i]; //and we switch these elements using TEMPORARY_ELEMENT
|
||||
ARRAY[i]=ARRAY[i+1];
|
||||
ARRAY[i+1]=TEMPORARY_ELEMENT;
|
||||
/*This is where the sorting of the array takes place
|
||||
arr[] --- Array to be sorted
|
||||
size --- Array Size
|
||||
*/
|
||||
void bubbleSort(int arr[], int size){
|
||||
|
||||
for(int i=0; i<size-1; i++) {
|
||||
for(int j=0; j<size-1; j++) {
|
||||
if(arr[j]>arr[j+1]) {
|
||||
swap(&arr[j], &arr[j+1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
//And we display it
|
||||
for(i=0;i<ARRAY_LENGTH;i++){
|
||||
printf("%d, ",ARRAY[i]);
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, const char * argv[]) {
|
||||
int n;
|
||||
printf("Enter size of array:\n");
|
||||
scanf("%d", &n); // E.g. 8
|
||||
|
||||
printf("Enter the elements of the array\n");
|
||||
int i;
|
||||
int arr[n];
|
||||
for(i = 0; i < n; i++){
|
||||
scanf("%d", &arr[i] );
|
||||
}
|
||||
|
||||
printf("Original array: ");
|
||||
display(arr, n); // Original array : 10 11 9 8 4 7 3 8
|
||||
|
||||
bubbleSort(arr, n);
|
||||
|
||||
printf("Sorted array: ");
|
||||
display(arr, n); // Sorted array : 3 4 7 8 8 9 10 11
|
||||
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user