Optimizing the algorithm, and improving the array filling

This commit is contained in:
Mehdi ALAOUI 2017-04-04 03:29:30 +01:00
parent 7b302b48cd
commit 382f084834

View File

@ -1,37 +1,40 @@
/* ALGORITHM #include <stdio.h>
1. Start from left hand side #include <stdlib.h>
2. Compare first two numbers
3. If first_number > second_number than swap both number position. And if first_number < second_number than these compare next two numbers i.e. second_number and third_number.
4. Step-3 process repeat until there are no more numbers left to compared.
*/
#include<stdio.h>
#include<conio.h> int main(){
#include<stdlib.h>
int main() int* ARRAY=NULL;
{ int ContinueFilling=1; //This is to know if we should continue filling our array
int i,j,temp,SIZE; int ARRAY_LENGTH=0,isSorted=0,i,TEMPORARY_ELEMENT;
printf("Enter number of elements to be sorted : ");
scanf("%d",&SIZE); //This code part is for filling our array
int *arr = (int*)malloc(SIZE*sizeof(int)); while(ContinueFilling){
for(i=0; i<SIZE; i++) printf("Enter the value number %d \n",ARRAY_LENGTH+1);
{ ARRAY=(int *)realloc(ARRAY,sizeof(int)*(ARRAY_LENGTH));
printf("Enter Number : "); scanf("%d",&ARRAY[ARRAY_LENGTH]);
scanf("%d",&arr[i]); ARRAY_LENGTH+=1;
} printf("would you enter an other value (1:Continue/0:Sort the actual array)?\n");
for(i=0; i<SIZE ; i++) scanf("%d",&ContinueFilling);
{ }
for(j=0; j<(SIZE-1)-i; j++)
{ //Then we sort it using Bubble Sort..
if( arr[j] < arr[j+1] )
{ while(!isSorted){ //While our array's not sorted
temp=arr[j]; isSorted=1; //we suppose that it's sorted
arr[j]=arr[j+1]; for(i=0;i<ARRAY_LENGTH-1;i++){ //then for each element of the array
arr[j+1]=temp; 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
printf("%d\t",arr[j]); ARRAY[i]=ARRAY[i+1];
} ARRAY[i+1]=TEMPORARY_ELEMENT;
getch(); }
return 0; }
} }
//And we display it
for(i=0;i<ARRAY_LENGTH;i++){
printf("%d, ",ARRAY[i]);
}
return 0;
}