Advertisement
Farid_Mia59

qkll

Nov 2nd, 2019
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.05 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. class node
  6. {
  7. public:
  8. int data;
  9. node * next;
  10. };
  11.  
  12. node * newnode (int x);
  13. void quicksort(node ** begin, node ** end);
  14.  
  15. int main (void)
  16. {
  17. int foo,n,i,j,k;
  18. node * temp;
  19. node * head = NULL;
  20. node * tail = NULL;
  21. cout<<"How many nodes do you want to insert\n";
  22. cin>>n;
  23. cout<<"Enter data of linked list\n";
  24. for ( i = 0; i < n; i++ )
  25. {
  26. cin>>foo;
  27. node * bar;
  28. if (head == NULL)
  29. {
  30. head = newnode(foo);
  31. tail = head;
  32. }
  33. else
  34. {
  35. bar = newnode(foo);
  36. tail->next = bar;
  37. tail = bar;
  38. }
  39. }
  40. cout<<"The linkedlist that you entered is as follows\n"; // Taking input
  41. temp = head;
  42. node * prev = NULL;
  43. while (temp != NULL)
  44. {
  45. cout<<temp->data<<"\t";
  46. prev = temp;
  47. temp = temp->next;
  48. }
  49. cout<<"\n";
  50. cout<<"Sorting the linked list now\n"; // Calling sort function
  51. quicksort(&head,&prev);
  52. temp = head;
  53. while (temp != NULL) // Printing output
  54. {
  55. cout<<temp->data<<"\t";
  56. temp = temp->next;
  57. }
  58. return 0;
  59. }
  60.  
  61. node * newnode (int x) // for allocating a new node
  62. {
  63. node * foo = new node;
  64. foo->data = x;
  65. foo->next = NULL;
  66. return foo;
  67. }
  68.  
  69. void quicksort(node ** begin, node ** end) // actual sort function
  70. {
  71. if (*begin == *end)
  72. return;
  73.  
  74. node * pivot = *begin;
  75. node * temp = *begin;
  76. temp = temp->next; // for pointing to next element
  77.  
  78. while (temp != *end)
  79. {
  80. if (temp->data < pivot->data)
  81. {
  82. node * temp1 = *begin; // swapping the two nodes if less than pivot
  83. *begin = temp;
  84. temp = temp->next;
  85. (*begin)->next = temp1;
  86. }
  87. else
  88. temp = temp->next; //else moving to next
  89. }
  90. quicksort(begin,&pivot); // calling for remaining elements (first half)
  91. quicksort(&(pivot->next),end); //for second half
  92. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement