Table of Contents
Use bubble sorting technique to sort the array in ascending order
algorithm
Example
Output
Sort the array in ascending order using selection sort technique
in conclusion
Home Backend Development C++ C++ program: Sort array elements in ascending order

C++ program: Sort array elements in ascending order

Sep 13, 2023 am 08:49 AM
array sort Ascending order

C++ program: Sort array elements in ascending order

In order to solve some problems effectively, it is very important to arrange the data items in the correct position order. One of the most popular permutation problems is the element ordering problem. this This article will demonstrate how to sort array members in ascending order in C (according to value keeps rising).

To arrange numeric or non-numeric elements in a specific order, there are many ways Sorting algorithms can be used in this area. Just two simple sorting techniques will be introduced in this article. Selection sort and bubble sort. Let us check them one by one Use appropriate technology and C implementation code alone.

Use bubble sorting technique to sort the array in ascending order

One of the most popular and straightforward ways to sort array components is Bubble sort method. In this method, two elements are checked sequentially to See if they are in the correct order. If not, the method swaps elements until they The order is correct. After that, move to the right and repeat the process with the other group values. Individual elements are placed in the correct expected position at the end Each of the several stages of bubble sorting technology. Look at bubble sort algorithm.

algorithm

  • Read array A and its size n as input
  • For i ranging from 0 to n-1, execute
    • For j ranging from 0 to n - 2, execute
      • If A[j] > A[j 1], then
        • Exchange A[j] and A[j 1]
      • If it ends
    • Finish
  • Finish

Example

#include <iostream>
using namespace std;
void display( int arr[], int n ){
   for ( int i = 0; i < n; i++ ) {
      cout << arr[i] << ", ";
   }
}
void swap ( int &a, int &b ){
   int temp = a;
   a = b;
   b = temp;
}
void solve( int arr[], int n ){
   int i, j;
   for ( i = 0; i < n; i++ ) {
      for ( j = 0; j < n-1; j++ ) {
         if ( arr[j] > arr[ j+1 ] ) {
            swap( arr[j], arr[ j + 1 ] );
         }
      }
   }
}
int main(){
   int arr[] = {8, 45, 74, 12, 10, 36, 58, 96, 5, 2, 78, 44, 25, 12, 89, 95, 63, 84};
   int n = sizeof( arr ) / sizeof( arr[0] );
   cout << "Array before sorting: ";
   display(arr, n);
   solve( arr, n );
   cout << "\nArray After sorting: ";
   display(arr, n);
}
Copy after login

Output

Array before sorting: 8, 45, 74, 12, 10, 36, 58, 96, 5, 2, 78, 44, 25, 12, 89, 95, 63, 84, 
Array After sorting: 2, 5, 8, 10, 12, 12, 25, 36, 44, 45, 58, 63, 74, 78, 84, 89, 95, 96, 
Copy after login
Copy after login

Sort the array in ascending order using selection sort technique

When using the selection sort strategy, we start from index I and go to the end Given an array, find the minimum or maximum element. Suppose we are Reveal each ingredient. It locates the smallest element from index I to the end At each stage, place the elements in place and repeat the process Find the next largest element from index I 1 and so on. These stages are about to be completed, Then the entire array will be sorted appropriately.

algorithm

  • Read array A and its size n as input
  • For i ranging from 0 to n-1, execute
    • ind := The smallest element index from i to n in A
    • If A[ i ] > A[ ind ], then
      • Exchange A[ i ] and A[ ind ]
    • If it ends
  • Finish

Example

#include <iostream>
using namespace std;
void display( int arr[], int n ){
   for ( int i = 0; i < n; i++ ) {
      cout << arr[i] << ", ";
   }
}
void swap ( int &a, int &b ){
   int temp = a;
   a = b;
   b = temp;
}
int min_index( int arr[], int n, int s, int e ){
   int min = 99999, min_ind = -1;
   for ( int i = s; i < e; i++ ) {
      if ( arr[i] < min ) {
         min = arr[i];
         min_ind = i;
      }
   }
   return min_ind;
}
void solve( int arr[], int n ){
   int i, j, ind;
   for ( i = 0; i < n; i++ ) {
      ind = min_index( arr, n, i, n );
      if ( arr[i] > arr[ ind ] ) {
         swap( arr[i], arr[ ind ] );
      }
   }
}
int main(){
   int arr[] = {8, 45, 74, 12, 10, 36, 58, 96, 5, 2, 78, 44, 25, 12, 89, 95, 63, 84};
   int n = sizeof( arr ) / sizeof( arr[0] );
   cout << "Array before sorting: ";
   display(arr, n);
   solve( arr, n );
   cout << "\nArray After sorting: ";
   display(arr, n);
}
Copy after login

Output

Array before sorting: 8, 45, 74, 12, 10, 36, 58, 96, 5, 2, 78, 44, 25, 12, 89, 95, 63, 84, 
Array After sorting: 2, 5, 8, 10, 12, 12, 25, 36, 44, 45, 58, 63, 74, 78, 84, 89, 95, 96, 
Copy after login
Copy after login

in conclusion

A basic problem is sorting, which involves arranging numbers or other items according to order Predetermined layout logic. There are many other sequencing techniques available in this field, But in this article, we’ll focus on two that are easy to use and understand. these two Sorting techniques include selection sorting technology and bubble sorting technology. We have Use these two techniques to arrange the data set in ascending (not descending) order. Although not very time efficient, these two sorting techniques are simple. both Both techniques require a time investment of O(n2), where n is enter. As long as it is judged whether there has been a change, there will be no change in subsequent stages There is no swapping at any stage, making bubble sort faster.

The above is the detailed content of C++ program: Sort array elements in ascending order. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to remove duplicate elements from PHP array using foreach loop? How to remove duplicate elements from PHP array using foreach loop? Apr 27, 2024 am 11:33 AM

The method of using a foreach loop to remove duplicate elements from a PHP array is as follows: traverse the array, and if the element already exists and the current position is not the first occurrence, delete it. For example, if there are duplicate records in the database query results, you can use this method to remove them and obtain results without duplicate records.

The Art of PHP Array Deep Copy: Using Different Methods to Achieve a Perfect Copy The Art of PHP Array Deep Copy: Using Different Methods to Achieve a Perfect Copy May 01, 2024 pm 12:30 PM

Methods for deep copying arrays in PHP include: JSON encoding and decoding using json_decode and json_encode. Use array_map and clone to make deep copies of keys and values. Use serialize and unserialize for serialization and deserialization.

PHP array key value flipping: Comparative performance analysis of different methods PHP array key value flipping: Comparative performance analysis of different methods May 03, 2024 pm 09:03 PM

The performance comparison of PHP array key value flipping methods shows that the array_flip() function performs better than the for loop in large arrays (more than 1 million elements) and takes less time. The for loop method of manually flipping key values ​​takes a relatively long time.

PHP array multi-dimensional sorting practice: from simple to complex scenarios PHP array multi-dimensional sorting practice: from simple to complex scenarios Apr 29, 2024 pm 09:12 PM

Multidimensional array sorting can be divided into single column sorting and nested sorting. Single column sorting can use the array_multisort() function to sort by columns; nested sorting requires a recursive function to traverse the array and sort it. Practical cases include sorting by product name and compound sorting by sales volume and price.

Best Practices for Deep Copying PHP Arrays: Discover Efficient Methods Best Practices for Deep Copying PHP Arrays: Discover Efficient Methods Apr 30, 2024 pm 03:42 PM

The best practice for performing an array deep copy in PHP is to use json_decode(json_encode($arr)) to convert the array to a JSON string and then convert it back to an array. Use unserialize(serialize($arr)) to serialize the array to a string and then deserialize it to a new array. Use the RecursiveIteratorIterator to recursively traverse multidimensional arrays.

Application of PHP array grouping function in data sorting Application of PHP array grouping function in data sorting May 04, 2024 pm 01:03 PM

PHP's array_group_by function can group elements in an array based on keys or closure functions, returning an associative array where the key is the group name and the value is an array of elements belonging to the group.

The role of PHP array grouping function in finding duplicate elements The role of PHP array grouping function in finding duplicate elements May 05, 2024 am 09:21 AM

PHP's array_group() function can be used to group an array by a specified key to find duplicate elements. This function works through the following steps: Use key_callback to specify the grouping key. Optionally use value_callback to determine grouping values. Count grouped elements and identify duplicates. Therefore, the array_group() function is very useful for finding and processing duplicate elements.

PHP array merging and deduplication algorithm: parallel solution PHP array merging and deduplication algorithm: parallel solution Apr 18, 2024 pm 02:30 PM

The PHP array merging and deduplication algorithm provides a parallel solution, dividing the original array into small blocks for parallel processing, and the main process merges the results of the blocks to deduplicate. Algorithmic steps: Split the original array into equally allocated small blocks. Process each block for deduplication in parallel. Merge block results and deduplicate again.

See all articles