0
void sort_int_array(int A[], int n) {
    int i, j, h, k, O[n];
    /* assume that A[0] to A[n-1] have valid values */
    for (i=1; i<n; i++) {
        /* swap A[i] left into correct position */
        for (j=i-1; j>=0 && A[j+1] <= A[j]; j--) {
            int_swap(&A[j], &A[j+1]);
            for (k=0; k<n; k++) {
                 for (h = 0; h < k; h++) {
                    if (A[k] == O[h]) {
                         break;
                    }
                    else {
                        O[k] = A[k];
                    }
                }
            }
        }   
    }
}   

I'm attempting to only write distinct values from a sorted array to another array. The first part of the function sorts the array however when I write it to my new array it returns the sorted array and doesn't remove the copies.

eg. Input: 4 5 6 7 6 5 4. Output: 4 4 5 5 6 6 7.

Output wanted: 4 5 6 7

3
  • Hope this is of use to you stackoverflow.com/questions/2826233/… Commented Jun 26, 2013 at 10:26
  • 4
    Try to do the sorting and the filtering separately otherwise your code gets cumbersome Commented Jun 26, 2013 at 10:26
  • Execute the 3rd and 4th for loop outside the 1st and 2nd for loop ,that should do the job. Commented Jun 26, 2013 at 12:02

2 Answers 2

0

You can try this way.

  1. Sort the array first. 4 4 5 5 6 6 7
  2. First element would always be distinct. Copy it in second array.
  3. Now, start from second element in sorted array, and copy after comparing with one element present in second array.
  4. If sorted[i]==output[j] , ignore or say increment i.
  5. Else, copy ith element to output array, increment both j and i
  6. Do this while you completely traversed your sorted array.

This will do the trick.

int[] arr = {4,4,5,5,6,6,7};
    int out[]= {0}; // or may be some size
    int i=1;
    out[0] = arr[0];
    int j=0;
    while(i<arr_length){
        if(arr[i]!=out[j]){
            out[++j]=arr[i];
        }
        i++;
    }
    for(int k=0;k<out_length;k++){
        printf("%d,",out[k]);
    }
Sign up to request clarification or add additional context in comments.

2 Comments

Very weird to use C++ (or at least what looks mostly like C++, with new) in a C answer.
thanks for the info. Edited now. Actually i wrote a java code previously and forgot to change
0
void sort_int_array(int A[], int n) {
    int i, j, k, O[n];
    for(k=i=0; i<n; ++i){
        for(j=i+1;j<n;++j){
            if(A[j]<A[i])
                int_swap(&A[j],&A[i]);
        }
        if(i==0 || O[k-1] < A[i])
            O[k++]=A[i];
    }
    printf("DEBUG:");
    for(i=0;i<k;++i)
        printf("%d ", O[i]);
    printf("\n");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.