Advertisement
Guest User

Untitled

a guest
Dec 10th, 2019
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.86 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. //#include <bits/stdc++.h>
  4. using namespace std;
  5.  
  6. void swap(int* a, int* b)
  7. {
  8.     int t = *a;
  9.     *a = *b;
  10.     *b = t;
  11. }
  12.  
  13. /* This function takes last element as pivot, places
  14. the pivot element at its correct position in sorted
  15. array, and places all smaller (smaller than pivot)
  16. to left of pivot and all greater elements to right
  17. of pivot */
  18. int partition(int arr[], int low, int high)
  19. {
  20.     int pivot = arr[high]; // pivot  
  21.     int i = (low - 1); // Index of smaller element  
  22.  
  23.     for (int j = low; j <= high - 1; j++)
  24.     {
  25.         // If current element is smaller than the pivot  
  26.         if (arr[j] < pivot)
  27.         {
  28.             i++; // increment index of smaller element  
  29.             swap(&arr[i], &arr[j]);
  30.         }
  31.     }
  32.     swap(&arr[i + 1], &arr[high]);
  33.     return (i + 1);
  34. }
  35.  
  36. /* The main function that implements QuickSort
  37. arr[] --> Array to be sorted,
  38. low --> Starting index,
  39. high --> Ending index */
  40. void quickSort(int arr[], int low, int high)
  41. {
  42.     if (low < high)
  43.     {
  44.         /* pi is partitioning index, arr[p] is now
  45.         at right place */
  46.         int pi = partition(arr, low, high);
  47.  
  48.         // Separately sort elements before  
  49.         // partition and after partition  
  50.         quickSort(arr, low, pi - 1);
  51.         quickSort(arr, pi + 1, high);
  52.     }
  53. }
  54.  
  55. /* Function to print an array */
  56. void printArray(int arr[], int size)
  57. {
  58.     ofstream data;
  59.     data.open("sorted.txt");
  60.  
  61.     for (int i = 0; i < size; i++)
  62.     {
  63.         if (i % 100 == 0) data << endl;
  64.  
  65.         data << arr[i] << " ";
  66.     }
  67.  
  68.     data << endl << endl;
  69.  
  70.     data << "Is viso surikiuota: " << size << " skaiciu." << endl;
  71.  
  72.     data.close();
  73. }
  74.  
  75. int main()
  76. {
  77.     ifstream input;
  78.    
  79.     input.open("output.txt");
  80.  
  81.     int arr[100000];
  82.  
  83.     int j = 0;
  84.  
  85.     while (input)
  86.     {
  87.         input >> arr[j];
  88.         j++;
  89.     }
  90.  
  91.     int n = sizeof(arr) / sizeof(arr[0]);
  92.  
  93.     quickSort(arr, 0, n - 1);
  94.  
  95.     cout << "Pavyko!" << endl;
  96.  
  97.     printArray(arr, n);
  98.  
  99.     input.close();
  100.  
  101.     return 0;
  102. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement