Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- sort_matrix_extract_unique_elements.c
- Sort the matrix and extract the unique elements.
- https://www.faceprep.in/c/program-to-remove-duplicate-elements-in-an-array/
- You can find all my C programs at Dragan Milicev's pastebin:
- https://pastebin.com/u/dmilicev
- */
- #include <stdio.h>
- #define MAX_SIZE 10
- //#define ROWS 10
- //#define COLUMNS 10
- // Displays array arr[] that has n elements
- // text[] describes the shown array arr[]
- void display_array(char text[],int arr[],int n)
- {
- int i;
- printf("%s",text);
- for(i=0;i<n;i++)
- printf("%4d", arr[i]);
- printf("\n");
- }
- // Displays a matrix M [] [] that has r rows and c columns
- void display_matrix( char *text, int M[][MAX_SIZE], int r, int c )
- {
- int i, j;
- printf("\n%s\n\n",text);
- for(i=0;i<r;i++) { // print matrix M[][]
- for(j=0;j<c;j++)
- printf(" %4d", M[i][j]);
- printf("\n\n"); // new row of matrix
- }
- }
- // function bubbleSort to sort the array arr[] of n elements in descending order
- void bubbleSort(int arr[], int n)
- {
- int i, j, temp;
- for (i = 0; i < n-1; i++)
- for (j = 0; j < n-i-1; j++) // Last i elements are already in place
- if (arr[j] < arr[j+1]) // arr[j] > arr[j+1] for ascending order
- {
- temp = arr[j];
- arr[j] = arr[j+1];
- arr[j+1] = temp;
- }
- }
- // remove duplicate elements in an sorted array
- int remove_duplicate_elements(int arr[], int n)
- {
- if (n==0 || n==1)
- return n;
- int temp[n];
- int j = 0;
- int i;
- for (i=0; i<n-1; i++)
- if (arr[i] != arr[i+1])
- temp[j++] = arr[i];
- temp[j++] = arr[n-1];
- for (i=0; i<j; i++)
- arr[i] = temp[i];
- return j;
- }
- int main(void)
- {
- int i, j, k=0, r=3, c=3, n=r*c;
- // r is the number of rows and c is the number of columns of the matrix M[][]
- int M[MAX_SIZE][MAX_SIZE] = { { 5, 4, 5 },
- { 2, 0, 4 },
- { 1, 5, 2 } }; // matrix
- int arr[n]; // array
- // collecting matrix elements in an array
- for(i=0; i<r; i++)
- for(j=0; j<c; j++)
- arr[k++] = M[i][j];
- display_matrix(" \n MATRIX = \n", M, r, c);
- display_array("\n\tARRAY = ", arr, n);
- bubbleSort(arr,r*c);
- display_array("\n SORTED ARRAY = ", arr, n);
- n = remove_duplicate_elements(arr,n);
- display_array("\n UNIQUE ARRAY = ", arr, n);
- return 0;
- } // main()
Advertisement
RAW Paste Data
Copied
Advertisement