logo
Tags down

shadow

Iterative quicksort method


By : Ahmet Emre Gürcan
Date : July 31 2020, 10:00 PM
help you fix your problem I'm trying to implement a hoare quicksort method that runs iterativly. Im using the Algorithm below. So right now it inputs: 10 7 8 9 1 5 and for example when i run it outputs: 5 7 8 9 1 10 it only switches 2 elements from the array. Why does it stop? Where did i go wrong? , Several things are wrong here.
code :
right[0]=a[N-1];   # <-------------- pretty sure this should just be N-1, not a[N-1]


Share : facebook icon twitter icon

Looking at Sorts - Quicksort Iterative?


By : user2544508
Date : March 29 2020, 07:55 AM
Does that help I'm looking at all different sorts. Note that this is not homework (I'm in the midst of finals) I'm just looking to be prepared if that sort of thing would pop up. I was unable to find a reliable method of doing a quicksort iteratively. Is it possible and, if so, how?
code :
#include <stdio.h>
#include <conio.h>

#define MAXELT          100
#define INFINITY        32760         // numbers in list should not exceed
                                      // this. change the value to suit your
                                      // needs
#define SMALLSIZE       10            // not less than 3
#define STACKSIZE       100           // should be ceiling(lg(MAXSIZE)+1)

int list[MAXELT+1];                   // one extra, to hold INFINITY

struct {                              // stack element.
        int a,b;
} stack[STACKSIZE];

int top=-1;                           // initialise stack

int main()                           // overhead!
{
    int i=-1,j,n;
    char t[10];
    void quicksort(int);

    do {
        if (i!=-1)
            list[i++]=n;
        else
            i++;
        printf("Enter the numbers <End by #>: ");
        fflush(stdin);
        scanf("%[^\n]",t);
        if (sscanf(t,"%d",&n)<1)
        break;
    } while (1);

    quicksort(i-1);

    printf("\nThe list obtained is ");
    for (j=0;j<i;j++)
        printf("\n %d",list[j]);

    printf("\n\nProgram over.");
    getch();
    return 0;       // successful termination.
}

void interchange(int *x,int *y)        // swap
{
    int temp;

    temp=*x;
    *x=*y;
    *y=temp;
}

void split(int first,int last,int *splitpoint)
{
    int x,i,j,s,g;

    // here, atleast three elements are needed
    if (list[first]<list[(first+last)/2]) {  // find median
        s=first;
        g=(first+last)/2;
    }
    else {
        g=first;
        s=(first+last)/2;
    }
    if (list[last]<=list[s]) 
        x=s;
    else if (list[last]<=list[g])
        x=last;
    else
        x=g;
    interchange(&list[x],&list[first]);      // swap the split-point element
                                             // with the first
    x=list[first];
    i=first+1;                               // initialise
    j=last+1;
    while (i<j) {
        do {                                 // find j 
            j--;
        } while (list[j]>x);
        do {
            i++;                             // find i
        } while (list[i]<x);
        interchange(&list[i],&list[j]);      // swap
    }
    interchange(&list[i],&list[j]);          // undo the extra swap
    interchange(&list[first],&list[j]);      // bring the split-point 
                                             // element to the first
    *splitpoint=j;
}

void push(int a,int b)                        // push
{
    top++;
    stack[top].a=a;
    stack[top].b=b;
}

void pop(int *a,int *b)                       // pop
{
    *a=stack[top].a;
    *b=stack[top].b;
    top--;
}

void insertion_sort(int first,int last)
{
    int i,j,c;

    for (i=first;i<=last;i++) {
        j=list[i];
        c=i;
        while ((list[c-1]>j)&&(c>first)) {
            list[c]=list[c-1];
            c--;
        }
        list[c]=j;
    }
}

void quicksort(int n)
{
    int first,last,splitpoint;

    push(0,n);
    while (top!=-1) {
        pop(&first,&last);
        for (;;) {
            if (last-first>SMALLSIZE) {
                // find the larger sub-list
                split(first,last,&splitpoint);
                // push the smaller list
                if (last-splitpoint<splitpoint-first) {
                    push(first,splitpoint-1);
                    first=splitpoint+1;
                }
                else {
                    push(splitpoint+1,last);
                    last=splitpoint-1;
                }
            }
            else {  // sort the smaller sub-lists
                    // through insertion sort
                insertion_sort(first,last);
                break;
            }
        }
    }                        // iterate for larger list
}

// End of code.

Quicksort: Iterative or Recursive


By : Deepak Chandrasekara
Date : March 29 2020, 07:55 AM
With these it helps In terms of (asymptotic) time complexity - they are both the same.
"Recursive is slower then iterative" - the rational behind this statement is because of the overhead of the recursive stack (saving and restoring the environment between calls).
code :
public static void recursiveQsort(int[] arr,Integer start, Integer end) { 
    if (end - start < 2) return; //stop clause
    int p = start + ((end-start)/2);
    p = partition(arr,p,start,end);
    recursiveQsort(arr, start, p);
    recursiveQsort(arr, p+1, end);

}

public static void iterativeQsort(int[] arr) { 
    Stack<Integer> stack = new Stack<Integer>();
    stack.push(0);
    stack.push(arr.length);
    while (!stack.isEmpty()) {
        int end = stack.pop();
        int start = stack.pop();
        if (end - start < 2) continue;
        int p = start + ((end-start)/2);
        p = partition(arr,p,start,end);

        stack.push(p+1);
        stack.push(end);

        stack.push(start);
        stack.push(p);

    }
}

private static int partition(int[] arr, int p, int start, int end) {
    int l = start;
    int h = end - 2;
    int piv = arr[p];
    swap(arr,p,end-1);

    while (l < h) {
        if (arr[l] < piv) {
            l++;
        } else if (arr[h] >= piv) { 
            h--;
        } else { 
            swap(arr,l,h);
        }
    }
    int idx = h;
    if (arr[h] < piv) idx++;
    swap(arr,end-1,idx);
    return idx;
}
private static void swap(int[] arr, int i, int j) { 
    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
}

public static void main(String... args) throws Exception {
    Random r = new Random(1);
    int SIZE = 1000000;
    int N = 100;
    int[] arr = new int[SIZE];
    int[] millisRecursive = new int[N];
    int[] millisIterative = new int[N];
    for (int t = 0; t < N; t++) { 
        for (int i = 0; i < SIZE; i++) { 
            arr[i] = r.nextInt(SIZE);
        }
        int[] tempArr = Arrays.copyOf(arr, arr.length);

        long start = System.currentTimeMillis();
        iterativeQsort(tempArr);
        millisIterative[t] = (int)(System.currentTimeMillis()-start);

        tempArr = Arrays.copyOf(arr, arr.length);

        start = System.currentTimeMillis();
        recursvieQsort(tempArr,0,arr.length);
        millisRecursive[t] = (int)(System.currentTimeMillis()-start);
    }
    int sum = 0;
    for (int x : millisRecursive) {
        System.out.println(x);
        sum += x;
    }
    System.out.println("end of recursive. AVG = " + ((double)sum)/millisRecursive.length);
    sum = 0;
    for (int x : millisIterative) {
        System.out.println(x);
        sum += x;
    }
    System.out.println("end of iterative. AVG = " + ((double)sum)/millisIterative.length);
}

How do I change iterative quicksort with fixed pivot to iterative quicksort with random pivot?


By : Fapricorn
Date : March 29 2020, 07:55 AM
hope this fix your issue Your partition function assumes the pivot is at the end of the partition. Consider moving your random pivot to the end of the partition first.
i.e. add
code :
swap(&arr[r], &arr[h]);

Is a Recursive-Iterative Method Better than a Purely Iterative Method to find out if a number is prime?


By : aurobinda jena
Date : March 29 2020, 07:55 AM
seems to work fine Since your program tests just one number, you're wasting time trying to avoid testing by composites. You perform a lot of computations to save one meager modulo operation.
If you were testing more than a few numbers in a row for primality, then it would make sense to pre-compute the primes up to a sqrt of the top limit of that range, and go through those primes when testing the candidates.
code :
Input: two Integers n >= m > 1

Let k = Floor(Sqrt(n)),
Let A be an array of Boolean values, indexed by Integers 2 to k, and
    B an array of Booleans indexed by Integers from m to n,
    initially all set to True.

for i = 2, 3, 4, ..., not exceeding k:
  if A[i] is True:
    for j = i^2, i^2+i, i^2+2i, ..., not greater than k:
      A[j] := False
    for j = i^2, i^2+i, i^2+2i, ..., between m and n, inclusive:
      B[j] := False

Output: all `i`s such that B[i] is True, are all the primes 
                                     between m and n, inclusive.

How to do iterative quicksort without using stack in c?


By : Tom S.
Date : March 29 2020, 07:55 AM
seems to work fine First of all does C have a stack class? ,
First of all does C have a stack class?
Related Posts Related Posts :
  • Java EE 7 batch API (JSR-352): it's possible to stop a single step and not all the job?
  • Java multithread example - is object shared or not
  • Why String's replaceAll() method come at high performance cost at the first time and faster at the next time?
  • Lua script coverts empty array to object
  • Doesn't Access to external storage in API-29
  • How to add a button to the Android system navigation bar?
  • If inside for-each-loop to Stream
  • Shift array to the right by one slot
  • How to setup a Java development environment for Z3
  • how to make notify() works properly with wait()
  • IllegalFormatConversionException d != java.lang.Integer when trying to printf date?
  • Duplicate logic in backend and frontend with Domain Driven Design
  • How would I randomize an int[][]?
  • StringDate to Date coming in different Time in SimpleDateFormat in java
  • Get content uri from file path in android for video
  • function param issue in Scala 11, works in Scala 12 using resilience4j
  • Android unit testing : calling a method from fragment which uses context
  • How to remove E notation from Double value
  • Check if input is any of the values in an array
  • DateTimeParseException - could not be parsed at index 0
  • How to make a Java HTTP async request?
  • Make Javafx/Scenebuilder recognize tagged fields and methods when splitting the MainController into multiple files?
  • Why does this time fail to be parsed by DateTimeFormatter.ofPattern()?
  • Java - Merge objects of list given a condition
  • How to know if arraylist contains value in property of object?
  • Java modelling class if objects have same properties but they are fundamentally different
  • False Positive and False Negative
  • Java UnknownFormatConversionException = ','
  • Apache POI recording only 1 row in the spreadsheet
  • Getting Constructor from Java Class that would be called for argument types, not requiring exact argument & paramete
  • @JsonIgnore with Conditions
  • Does synchronizing on the static field that you are modifying make your code thread safe?
  • Compiler errors while trying to make a pop up
  • Trying to take two timestamps, subtract them, convert the difference to seconds and store in an int variable
  • How can I use Optionals instead of nested if statement?
  • How do I compare values in parallel arrays to eliminate duplicates?
  • make a method which returns the number of one digit numbers in an array
  • Does calling multiple times save() method of hibernate with same object insert new record in DB?
  • Single Number solving by Haspmap, return always be a "@"
  • What do you do about the JLabel classes? It says, "JLabel not a statement" for the error
  • Functional Interface call for a new Instance
  • When I tried to add ArrayList into ArrayList second ArrayList is repeating
  • How can I print the longest word from a user defined list?
  • enabling authentication in ignite
  • Providing OSGi Service Without Implementing Interface
  • Read manifest from JAR with gradle
  • Create one element Set the same way (if applicable) as create single element list
  • pass by reference an integer in java
  • how to generate the POI excel file in a specific location?
  • Issue trying to create a Bubble Sort using ArrayList<Integer>
  • How can I avoid typechecking in this situation
  • How to create a map<k,v> between first and last nested object using Java streams?
  • First time writing junit: Need suggestions
  • what is the best solution to split in chunk monthly given two dates startTime and EndTime in Java?
  • View Binding causes "The specified child already has a parent"
  • parse float in java with trailing junk
  • How to convert color from ColorPicker to String value in javaFX
  • Spring test integration not run how I deal with this error?
  • Java 8 Streams : Count the occurrence of elements(List<String> list1) from list of text data(List<String> li
  • What is the difference between static and protected in java?
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org