Showing posts with label Sort. Show all posts
Showing posts with label Sort. Show all posts

C Program Sort Example

How to write a C Program Sort in C Programming Language ?


Solution For C Program :

C Program Shell Sort Using C Programming Language

How to write a C Program For ShellSort Using C Programming Language ?

Shell sort is a sorting algorithm, devised by Donald Shell in 1959, that is a generalization of insertion
sort, which exploits the fact that insertion sort works efficiently on input that is already almost sorted. It improves on insertion sort by allowing the comparison and exchange of elements that are far apart.
The last step of Shell sort is a plain insertion sort, but by then, the array of data is guaranteed to be
almost sorted.

See More : Shellsort


Solution For C Program :
-------------------------------

SHELL SORT ALGORITHM 

-------------------------------
input: an array num of length n with array elements numbered 0 to n - 1

Shell.Sort(num,n,key)
1. Assign, span = int(n/2)
2. while span > 0 do:
   a) for i from span to n - 1, Repeat step b,c,e
   b) assign num[i] to key and i to j
   c) while j = span and num[j - span] > key, Repeat step d
   d) swap num[j] and num[j - span]
   e) Assign, span = int(span / 2.2)
3. Use Insertion Sort to sort remaining array of data
----------------------------------------------------------------------------

The following is an implementation of Shell sort written in pseudocode.
The increment sequence is a geometric sequence in which every term is
roughly 2.2 times smaller than the previous one:
---------------------

SHELL SORT PSEUDOCODE 

---------------------
span = int(n/2)
while span > 0 do:
for i = span .. n - 1 do:
   key =  num[i]
   j = i
   while j = span and num[j - span] > key do:
    num[j] = num[j - span]
    j = j - span
   num[j] = key
  span = int(span / 2.2)
****************************************************************************/

#include "iostream.h"
#include "conio.h"

void insertionSort(int num[],int N)
{
int i,j,key;
for(j = 1;j < N;j++) //From Second Element to Last
{
  key = num[j]; //Assign num[j] to key
   i = j - 1;
   while(i >= 0 && num[i] > key)
    {
     //Swap two elements
    num[i + 1] = num[i];
      i--;
      num[i + 1] = key;
    }
}
}

int main()
{
int num[50],N,i,j,span,key;
cout << "How many numbers? " ;
cin >> N;
cout << "\nEnter " << N << " Numbers\n";
for(i = 0;i < N;i++)
  cin >> num[i];

span = int(N/2);
while(span > 0)
  {
   for(i = span;i < N;i += span)
    {
     key = num[i];
     j = i;
     while(j >= span && num[j - span] > key)
      {
       num[j] = num[j - span];
       j = j - span;
      }

     num[j] = key;
    }
  span = int(span/2.2);
  }

//Now, the array of data is almost sorted
//So, using Insertion Sort as last step
insertionSort(num,N);

cout << endl;
for(int i = 0;i < N;i++)
  cout << num[i] << ' ';

getch();
return 0;
}

OUTPUT of C Program Shell Sort :
How many numbers? 10
Enter 10 Numbers 
25 65 47 88 64 10 -98 0 35 6
-98 0 6 10 25 35 47 64 65 88

C Program Selection Sort Using C Programming Language

How to write a C Program For Selection Sort Using C Programming Language ?

In computer scienceselection sort is a sorting algorithm, specifically an in-place comparison sort. It has O(n2) time complexity, making it inefficient on large lists, and generally performs worse than the similar insertion sort. Selection sort is noted for its simplicity, and it has performance advantages over more complicated algorithms in certain situations, particularly where auxiliary memory is limited.

See More : Selection sort


Solution For C Program:

C Program to Bubble Sort Using C Programming Language

How to write a C Program to Bubble Sort in C Programming Language ?

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 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 sort order but may occasionally have some out-of-order elements nearly in position.

See More: Bubble sort

Solution For C Program :

Heap Sort Using C Programming Language

How to write a C Program Heap Sort Using C Programming Language ?

sorting algorithm that works by first organizing the data to be sorted into a special type of binary tree called a heap. The heap itself has, by definition, the largest value at the top of the tree, so the heap sort algorithm must also reverse the order.

A complete binary tree is a binary tree in which each non-leaf has two children and all the leaves are at the same depth from the root.

A nearly complete binary tree is a binary tree constructed from a complete binary tree by eliminating a number of nodes (possibly none) from right at the leaf level.

A heap is a node-labeled, nearly complete binary tree with a special property.

The (Binary) heap data structure is an array object that can be

viewed as a nearly complete binary tree.

See More : Heapsort

Solution For C Program :


C Program To Sort An Array In Ascending And Descending Order

How to write a C Program To Sort An Array In Ascending And Descending Order in C Programming Language ?


Solution For C Program :

/*C Program To Sort An Array In Ascending And Descending Order.*/

#include<stdio.h>
#include<conio.h>
void main()
    {
    int a[5],i,j,k,temp=0;
    clrscr();
    printf("How many numbers you want to store:=");
    scanf("%d",&k);
    printf("Enter numbers for in an array:=");
    for(i=0;i<k;i++)
       {
       scanf("%d",&a[i]);
       }
    for(i=1;i<k;i++)
       {
       for(j=1;j<k;j++)
          {
          if(a[j]>a[j-1])  //NOTE: we can simply replace '<' by '>' for ascending order.
         {
         temp=a[j-1];
         a[j-1]=a[j];
         a[j]=temp;
         }
          }
       }
    printf("The sorted array in descending order is:=\n");
    for(i=0;i<k;i++)
        {
        printf("\t%d",a[i]);
        }
    printf("\n\nThe sorted array in ascending order is:=\n");
    for(i=k-1;i>=0;i--)
        {
        printf("\t%d",a[i]);
        }
    getch();
    }


You may also learn these C Program/Code :

C Program To Swap Two Numbers Without Using Third Variable



C Program To Sort An Array Of Names In Alphabetical And Reverse Order

How to write a C Program To Sort An Array Of Names In Alphabetical And Reverse Order in C Programming Language ?


Solution For C Program :

/*C Program To Sort An Array Of Names In Alphabetical And Reverse Order.*/

#include<stdio.h>
#include<string.h>
#include<conio.h>
void main()
    {
    int i,j,k;
    char name[10][10],tname[10][10],temp[10];
    clrscr();
    printf("How many numbers you want to store:=");
    scanf("%d",&k);
    printf("Enter numbers for in an array:=");
       fflush(stdin);

    for(i=0;i<k;i++)
       {
       scanf("%s",name[i]);
       strcpy(tname[i],name[i]);
       }

    for(i=1;i<k;i++)
       {
       for(j=1;j<k;j++)
          {
          if(strcmpi(name[j],name[j-1])<0)
          {
          strcpy(temp,name[j-1]);
          strcpy(name[j-1],name[j]);
          strcpy(name[j],temp);
          }
          }
       }
    printf("The sorted names in alphabetical order [A to Z Format] are:\n");
    printf("\tOldlist\t\tNew list\n\n");
    for(i=0;i<k;i++)
        {
        printf("\t%s\t\t%s\n",tname[i],name[i]);
        }
    printf("\n\nThe sorted names in [Z to A Format] are:\n");
    for(i=k-1;i>=0;i--)
        {
        printf("\t%s\n",name[i]);
        }
    getch();
    }


You may also learn these C Program/Code :

C Program To Swap Two Numbers Without Using Third Variable



C Program Sort Array By Segment

How to write a C Program Sort Array By Segment in C Programming Language ?

This C Program Sort Array By Segment.

Solution:

  1.     #include <stdio.h>
  2.     #include <string.h>
  3.     #include <stdlib.h>
  4.     #include <pthread.h>
  5.      
  6.     struct SortParameters{
  7.             int *arr;
  8.             int begin;
  9.             int end;
  10.     };
  11.      
  12.      
  13.      
  14.      
  15.     void buildRandomArray(int *arr,int size);
  16.     void * sortArrayBySegment(void * params);
  17.     void printArray(int *arr,int size);
  18.     void Merge(int *A,int *L,int leftCount,int *R,int rightCount);
  19.     void MergeSort(int *A,int n);
  20.    
  21.     int main(){
  22.      
  23.              int size=0;
  24.              int cantH=0;
  25.         printf("Ingresar size del arreglo\n");
  26.         scanf("%d", &size);
  27.         printf("Ingresar cant de hilos\n");
  28.         scanf("%d", &cantH);
  29.         if(size % cantH != 0){
  30.           printf("%d no es divisible entre %d\n",size,cantH);
  31.           return -1;
  32.         }
  33.         int *arr=(int *)malloc(sizeof(int)*size);
  34.         buildRandomArray(arr,size);
  35.         int divsize = size / cantH;
  36.         struct SortParameters params;
  37.         pthread_t tid[cantH];
  38.         pthread_attr_t attr;
  39.         pthread_attr_init(&attr);
  40.        
  41.         params.begin = 0;
  42.         params.end = divsize;                
  43.         for (int i = 0; i < cantH; i++)
  44.         {      
  45.             params.arr = &arr[i*divsize];
  46.             pthread_create(&tid[i],&attr,sortArrayBySegment,&params);
  47.             pthread_join(tid[i],0);
  48.         }
  49.             printArray(arr,size);
  50.            // MergeSort(arr,size);
  51.            // printArray(arr,size);
  52.             printf("\n");
  53.      
  54.             return 0;
  55.     }
  56.      
  57.     void buildRandomArray(int *arr,int size){
  58.       for(int i =0;i<size;i++){
  59.                     arr[i]= rand()%1000+1;
  60.       }
  61.     }
  62.      
  63.     void * sortArrayBySegment(void * params){
  64.             printf("%s\n","Corriendo hilo...." );
  65.             struct SortParameters *parameters =(struct SortParameters*)params;
  66.             for(int i=parameters->begin;i<parameters->end;i++){
  67.                     for(int j=parameters->begin;j<parameters->end;j++){
  68.                             if(parameters->arr[i]<parameters->arr[j]){
  69.                                     int tmp=parameters->arr[i];
  70.                                     parameters->arr[i]=parameters->arr[j];
  71.                                     parameters->arr[j]=tmp;
  72.                             }
  73.                     }
  74.             }
  75.             pthread_exit(0);
  76.     }
  77.      
  78.     void printArray(int *arr,int size){
  79.              for(int i =0;i<size;i++){
  80.                     printf("%d ",arr[i]);
  81.       }
  82.      
  83.     }