Question

C++. This program is giving me a wrong quicksort sorting plz fix. use the function that...

C++. This program is giving me a wrong quicksort sorting plz fix. use the function that it already have. don't add new function comment everything that you do thanks

#include<iostream>
#include<cstdlib>

using namespace std;

// Intercambiar dos valores.
// Arranges the first, middle, and last entries in an array into ascending order.

void sortFirstMiddleLast(int a[], int first, int mid, int last) {
  
   if (a[first] > a[mid])
   {
       int temp;
       temp = a[first];
       a[first] = a[mid];
       a[mid] = temp;
   }

   if (a[mid] > a[last])
   {
       int temp;
       temp = a[mid];
       a[mid] = a[last];
       a[last] = temp;
   }

   if (a[first] > a[mid])
   {
       int temp;
       temp = a[first];
       a[first] = a[mid];
       a[mid] = temp;
   }

}

int Partition(int a[], int first, int last)
{
   int pivot, index,indexFromLeft,indexFromRight, i,done,temp;
   index = first;
   pivot = last;
       // Choose pivot and reposition it
   int mid = first + (last - first) / 2;
   sortFirstMiddleLast(a, first, mid, last);
   // interchange theArray[mid] and theArray[last – 1]
   if (a[mid] > a[last - 1])
   {
      
       temp = a[mid];
       a[mid] = a[last - 1];
       a[last - 1] = temp;
   }

   index = last - 1;
   pivot = a[index];
       // Determine the regions S 1 and S 2
   indexFromLeft = first + 1;
   indexFromRight = last - 2;
   done = false;
       while (!done)
       {
           // Locate first entry on left that is ≥ pivot
           while (a[indexFromLeft] < pivot)
               indexFromLeft = indexFromLeft + 1;
               // Locate first entry on right that is ≤ pivot
           while (a[indexFromRight] > pivot)
               indexFromRight = indexFromRight - 1;
           if (indexFromLeft < indexFromRight)
           {

  

               /*Move theArray[firstUnknown] into S1
                   Interchange theArray[indexFromLeft] and theArray[indexFromRight]
                   indexFromLeft = indexFromLeft + 1
                   indexFromRight = indexFromRight - 1*/
               a[first] = indexFromLeft;
               temp = a[indexFromLeft];
               a[indexFromLeft] = a[indexFromRight];
               a[indexFromRight] = temp;
               indexFromLeft = indexFromLeft + 1;
               indexFromRight = indexFromRight - 1;
           }
           else
               done = true;
       }
   // Place pivot in proper position between S 1 and S 2 , and mark its new location
   // Interchange theArray[pivotIndex] and theArray[indexFromLeft]
           temp = a[index];
           a[index] = a[indexFromLeft];
           a[indexFromLeft] = temp;
           index = indexFromLeft;
           return index;
      
  
}

// Implementacion QuickSort.
int QuickSort(int a[], int first, int last)
{
   //tomaremos el array lo particiamos (lo dividimos) y aplicaremos el mismo método de forma recursiva.
   int pindex;
   if (first < last)
   {
       // particion del array usando el pivot que se cogio al azar.
       pindex = Partition(a, first, last);
       // se implementa el QuickSort de forma recursiva.
       QuickSort(a, first, pindex - 1);
       QuickSort(a, pindex + 1, last);
   }
   // el tipo de retorno de esta funcion es int se returna 0
   return 0;
}

int main()
{
   int n, i;
   cout << "\nEnter the number of data element to be sorted: ";
   cin >> n;

   int arr[100];
   for (i = 0; i < n; i++)
   {
       cout << "Enter element " << i + 1 << ": ";
       cin >> arr[i];
   }

   QuickSort(arr, 0, n - 1);

   // La data guardada que ya esta sorted.
   cout << "\nSorted Data ";
   for (i = 0; i < n; i++)
       cout << "->" << arr[i];

   return 0;
}

Homework Answers

Answer #1

#include<iostream>
#include<cstdlib>

using namespace std;

// Swapping two values.
void swap(int *a, int *b)
{
   int temp;
   temp = *a;
   *a = *b;
   *b = temp;
}

// Partitioning the array on the basis of values at high as pivot value.
int Partition(int a[], int low, int high)
{
   int pivot, index, i;
   index = low;
   pivot = high;

   // Getting index of pivot.
   for(i=low; i < high; i++)
   {
       if(a[i] < a[pivot])
       {
           swap(&a[i], &a[index]);
           index++;
       }
   }
   // Swapping value at high and at the index obtained.
   swap(&a[pivot], &a[index]);

   return index;
}

// Random selection of pivot.
int RandomPivotPartition(int a[], int low, int high)
{
   int pvt, n, temp;
   n = rand();
   // Randomizing the pivot value in the given subpart of array.
   pvt = low + n%(high-low+1);

   // Swapping pvt value from high, so pvt value will be taken as pivot while partitioning.
   swap(&a[high], &a[pvt]);

   return Partition(a, low, high);
}

// Implementing QuickSort algorithm.
int QuickSort(int a[], int low, int high)
{
   int pindex;
   if(low < high)
   {
       // Partitioning array using randomized pivot.
       pindex = RandomPivotPartition(a, low, high);
       // Recursively implementing QuickSort.
       QuickSort(a, low, pindex-1);
       QuickSort(a, pindex+1, high);
   }
   return 0;
}

int main()
{
   int n, i;
   cout<<"\nEnter the number of data element to be sorted: ";
   cin>>n;

   int arr[n];
   for(i = 0; i < n; i++)
   {
       cout<<"Enter element "<<i+1<<": ";
       cin>>arr[i];
   }

   QuickSort(arr, 0, n-1);

   // Printing the sorted data.
   cout<<"\nSorted Data ";
   for (i = 0; i < n; i++)
           cout<<"->"<<arr[i];

   return 0;
}

Enter the number of data element to be sorted: 4
Enter element 1: 23
Enter element 2: 67
Enter element 3: 45
Enter element 4: 34

Sorted Data ->23->34->45->67

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
DIRECTIONS: IMPLEMENT QuickSort and MergeSort. You have been provided: 1. Functions to perform Merge (for MergeSort)...
DIRECTIONS: IMPLEMENT QuickSort and MergeSort. You have been provided: 1. Functions to perform Merge (for MergeSort) and Partition (for QuickSort). 2. In class we discussed the body of the recursive functions, the "brakes" needed to stop the recursion. You are expected to develop 2 RECURSIVE programs: 1. Complete the bodies of the sort functions, MergeSort and QuickSort. 2. Complate the main that tests each function. - program should not read inputs - stock the program with multiple arrays (test cases)...
C++ Converting from binary to decimal. Here's what i have. it doesn't work yet unfortunately. Fix?...
C++ Converting from binary to decimal. Here's what i have. it doesn't work yet unfortunately. Fix? #include <conio.h> // For function getch() #include <cstdlib> // For several general-purpose functions #include <fstream> // For file handling #include <iomanip> // For formatted output #include <iostream> // For cin, cout, and system #include <string> // For string data type using namespace std; // So "std::cout" may be abbreviated to "cout" int main() {       int n;    int a[10], i;    int...
Write a template-based class that implements a template-based implementation of Homework 3 that allows for any...
Write a template-based class that implements a template-based implementation of Homework 3 that allows for any type dynamic arrays (replace string by the template in all instances below). • The class should have: – A private member variable called dynamicArray that references a dynamic array of type string. – A private member variable called size that holds the number of entries in the array. – A default constructor that sets the dynamic array to NULL and sets size to 0....
c++ Language Fix this code to have it concatenate two strings st1 and st2 and put...
c++ Language Fix this code to have it concatenate two strings st1 and st2 and put the result in st3 with a space separator. it has to be done using array representation of strings #include <iostream> using namespace std; #include <string> int main() { string st1,st2, st3; int c = 0, i =0;    cout << "Enter a string: "; cin >> st1; cout << "Enter another string: "; cin >> st2;    while (st1[c] != '\0'){ st3[c] = st1[c];...
C++, I am not able to get this program to function correctly, ie not launching at...
C++, I am not able to get this program to function correctly, ie not launching at all #include <iostream> #include <stdio.h> int insert(int num, int location) { int parentnode; while (location > 0) { parentnode =(location - 1)/2; if (num <= array[parentnode]) { array[location] = num; return; } array[location] = array[parentnode]; location = parentnode; } array[0] = num; } int array[100], n; using namespace std; main() { int choice, num; n = 0; while(1) { printf("1.Insert the element \n"); printf("2.Delete...
You need to write a program that reads in two integers from cin and outputs a...
You need to write a program that reads in two integers from cin and outputs a horribly inefficient calculation of the median value. First, count from the first number to the second, but stop one short. Then, count from that number back towards the first, again stopping one short. Continue until you reach a single number. Enter: 3 9 Out: 3 4 5 6 7 8 9 9 8 7 6 5 4 4 5 6 7 8 8 7...
Do a theta analysis and count the number of computations it performed in each function/method of...
Do a theta analysis and count the number of computations it performed in each function/method of the following code: import java.io.*; import java.util.Scanner; class sort { int a[]; int n; long endTime ; long totalTime; long startTime; static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public sort(int nn) // Constructor { a = new int[nn]; n = nn; endTime= 0; totalTime =0; startTime =0; } public static void main(String args[]) throws IOException { System.out.print("\nEnter number of students: "); int nn =...
For some reason I followed the steps in my project and I am getting the incorrect...
For some reason I followed the steps in my project and I am getting the incorrect output and when I am submitting it, it gives me compilation error. Printing empty array -- next line should be blank Testing append: Shouldn't crash! Should print 100 through 110 below, with 110 on a new line: 100 101 102 103 104 105 106 107 108 109 110 Checking capacity of new array: OK Append test #2: Should print 100 through 120 below, on...
getting an error for the code below when attempting to compile . Not fully sure what...
getting an error for the code below when attempting to compile . Not fully sure what the error means and confused why I am getting the error. I know there are a of other logical errors but im just looking for the solution to this specific one right now. /tmp/ccq2rdty.o: In function `main': IntArrayPlay.cpp:(.text+0x42): undefined reference to `fillArray(int*, int&)' IntArrayPlay.cpp:(.text+0x55): undefined reference to `displayArray(int*, int&)' IntArrayPlay.cpp:(.text+0x114): undefined reference to `displayArray(int*, int&)' IntArrayPlay.cpp:(.text+0x15f): undefined reference to `displayArray(int*, int&)' collect2: error: ld...
my code has several functions; delete and backward functions are not working, rewrite the code for...
my code has several functions; delete and backward functions are not working, rewrite the code for both functions and check them in the main: #include<iostream> #include<cassert> using namespace std; struct nodeType {    int info;    nodeType *link; }; class linkedList { public:    void initializeList();    bool isEmptyList();    void print();    int length();    void destroyList();    void insertFirst(int newItem);    void insertLast(int newItem);    int front();    linkedList();    void copyList(const linkedList otherList);    void insertNewValue(int value);...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT