Change SelectionSort.c format

This commit is contained in:
sungbin 2018-11-08 16:04:04 +09:00
parent 326cf62a0f
commit bc1c15e24f

View File

@ -1,89 +1,64 @@
//sorting of linked list using selection sort //sorting of linked list using selection sort
#include<stdio.h> #include <stdio.h>
struct node
{ /*Displays the array, passed to this method*/
int info; void display(int arr[], int n){
struct node *link;
}; int i;
struct node *start=NULL; for(i = 0; i < n; i++){
//func to create node printf("%d ", arr[i]);
struct node *createnode() }
{
struct node *p; printf("\n");
p=(struct node*)malloc(sizeof(struct node));
return(p);
} }
//program to insert at begining
void insert() /*Swap function to swap two values*/
{struct node *t; void swap(int *first, int *second){
t=createnode();
printf("\nenter the value to insert"); int temp = *first;
scanf("%d",&t->info); *first = *second;
if(start==NULL) *second = temp;
{start=t;
} }
else
{strutc node *p; /*This is where the sorting of the array takes place
p=start; arr[] --- Array to be sorted
t->link=p; size --- Array Size
start=t; */
} void selectionSort(int arr[], int size){
//program to sort the linked list using selection sort
void sort() for(int i=0; i<size; i++) {
{ int min_index = i;
struct node *p,*t; for(int j=i+1; j<size; j++) {
t=start; if(arr[min_index] > arr[j]) {
int tmp; min_index = j;
for(t=start;t->link!=NULL;t=t->link) }
{ }
for(p=t->link;p!=NULL;p=p->link) swap(&arr[i], &arr[min_index]);
{ }
if(t->info>p->info) }
tmp=t->info;
t->info=p->info; int main(int argc, const char * argv[]) {
p->info=tmp; int n;
} printf("Enter size of array:\n");
} scanf("%d", &n); // E.g. 8
//program to view sorted list
void viewlist() printf("Enter the elements of the array\n");
{ int i;
struct node *p; int arr[n];
if(start==NULL) for(i = 0; i < n; i++){
{ scanf("%d", &arr[i] );
printf("\nlist is empty"); }
}
else printf("Original array: ");
{ display(arr, n); // Original array : 10 11 9 8 4 7 3 8
p=start;
while(p!=NULL) selectionSort(arr, n);
{
printf("%d",p->info); printf("Sorted array: ");
p=p->link; display(arr, n); // Sorted array : 3 4 7 8 8 9 10 11
}
} return 0;
int main() }
{
int n;
whhile(1)
{
printf("\n1.insert value at beg");
printf("\n2.sort the list");
printf("\n3.view value");
printf("\nenter your choice");
scanf("%d",&n);
switch(n)
{case 1:
insert();
break;
case 2:
sort();
break;
case 3:
viewlist();
break;
default:
printf("\ninvalid choice");
}
}
return(0);
}