C-Sort an array (by pointers of pointers)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.