The advantage of ordering the actual array elements through pointers to pointers, and an array of pointers, is that the ordering process swaps only the values in the pointer array, not the elements of the actual array. This is beneficial when the objects in the actual element are large, especially those types, such as structs.
The following figure shows the changes in memory before and after sorting:
The following code is the implementation:
1#include <stdio.h>2 3 #defineSIZE 54 5 //here, sort by bubbling.6 void7Bubblesort (int**PARR) {8 int*tmp;9 intIsswap;//identifies whether the sort process is swapping (0 for no interchange, 1 for interchange).Ten for(inti =0; I < SIZE-1; i++) { OneIsswap =0; A for(intj =0; J < SIZE-1I J + +) { - if(* * (PARR + j) > * * (PARR + j +1)) { -TMP = * (PARR +j); the* (PARR + j) = * (PArr + j +1); -* (PARR + j +1) =tmp; - -Isswap =1;//identifies the interchange operation. + } -}//For (j). + if(!isswap) Break;//indicates a good order. A } at } - - //prints an array of actual elements. - void -Showint**p) { - for(inti =0; i < SIZE; i++) inprintf"%d", * * (P +i)); -printf"\ n"); to } + - int theMainvoid) { * intA[] = {7,4,8,1,9};//The actual array. $ int*parr[size];//an array of pointers, with each element corresponding to one by one in the actual array.Panax Notoginseng int**p = PARR;//A pointer to the first address of an array of pointers. - the for(inti =0; i < SIZE; i++) +Parr[i] = &a[i];//assigns a value to the elements of a pointer array. A theprintf"before sorting:\n"); + Show (p); - Bubblesort (p); $printf"After sorting:\n"); $ Show (p); -}
Output
before sorting: 7 4 8 1 9 After sorting: 1 4 7 8 9
C-Sort an array (by pointers of pointers)