Hello guys,
I wrote a code to bubble sort the elements of a linked list and its below. I couldn't understand how to apply bubble sort to a list so I copied the list's nodes into an array and applied bubble sort on that array (traditional method).
I was curious whether this code is 'EFFICIENT', like a good programming practice?
And how to apply bubble sort directly to linked list?
Here's the code:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// --- FUNCTION PROTOTYPES ---
void create_node();
void remove_newline();
char append();
void display();
// GLOBAL VARIABLES
int x=1;
int array[9];
// --- LIST ---
struct numbers
{
int num;
struct numbers *next;
};
struct numbers *first_node;
struct numbers *current_node;
struct numbers *new_node;
struct numbers *temp;
struct numbers *array_node;
int main()
{
printf("Hello!, input the numbers: \n");
first_node=(struct numbers *)malloc(sizeof(struct numbers));
if(first_node== NULL)
{
puts("Memory allocation failed!");
return(0);
}
current_node=first_node;
printf("Input the #%d value: ", x);
scanf("%d", ¤t_node->num);
remove_newline();
char choice=append();
while(choice == 'y' || choice== 'Y')
{
x++;
create_node();
remove_newline();
choice = append();
if( choice == 'n' || choice == 'N')
{
current_node->next=NULL;
new_node->next=NULL;
printf("Okay, then. Bye\n");
}
}
display();
printf("\nTOTAL NUMBER OF NODES: %d",x);
putchar('\n');
// --- LIST TO ARRAY ---
int i,array[x];
array_node=first_node;
for(i=0;i<x;i++)
{
array[i]= (array_node->num);
array_node=array_node->next;
}
// --- BUBBLE SORT ---
printf("Bubble sorted: \n");
int outer,inner,tmp;
for(outer=0;outer<x-1;outer++)
{
for(inner=outer+1;inner<x;inner++)
{
if(array[outer]>array[inner])
{
tmp=array[outer];
array[outer]=array[inner];
array[inner]=tmp;
}
}
}
for(i=0;i<x;i++)
{
printf("%d\t",array[i]);
}
return(0);
}
//--- FUNCTIONS ---
void create_node()
{
new_node=(struct numbers*)malloc(sizeof(struct numbers));
current_node->next=new_node;
if(new_node==NULL)
{
puts("Memory allocation failed");
}
current_node=new_node;
printf("Input #%d number: \n",x);
scanf("%d",¤t_node->num);
}
void remove_newline()
{
while(getchar() != '\n')
;
}
char append()
{
printf("\nDo you want to add more numbers in the list? Y/N: ");
char choice;
scanf("%c", &choice);
putchar('\n');
return(choice);
}
void display()
{
printf("Here is the list: \n");
temp=first_node;
while(temp!= NULL)
{
printf("%d\t",temp->num);
temp=temp->next;
}
}
Thanks.
EDIT: Yes I know that I shouldn't typecast malloc()