Programma C per ordinare un array usando i puntatori

Programma C per ordinare un array usando i puntatori

Scrivete un programma C per inserire gli elementi in un array e ordinarlo usando i puntatori. Come ordinare un array in ordine crescente o decrescente utilizzando i puntatori a funzione nella programmazione C. Logica per ordinare un array usando i puntatori nel programma.

Esempio

Inserimento

Input array elements: 10 -1 0 4 2 100 15 20 24 -5

Uscita

Array in ascending order: -5, -1, 0, 2, 4, 10, 15, 20, 24, 100,
Array in descending order: 100, 24, 20, 15, 10, 4, 2, 0, -1, -5,

Conoscenze richieste

Programmazione C di base, Array, Funzioni, Puntatori, Puntatori a funzione

Logica per ordinare un array usando i puntatori

Di seguito è riportata la logica descrittiva passo passo per ordinare un array utilizzando il puntatore.

  1. Inserisci la dimensione e gli elementi nell'array. Memorizzateli in qualche variabile, ad esempio size e arr .
  2. Dichiara due funzioni con prototipo int sortAscending(int * num1, int * num2) e int sortDescending(int * num1, int * num2) .

    Entrambe le funzioni vengono utilizzate per confrontare due elementi e disporli in ordine crescente o decrescente. sortAscending() restituisce un valore negativo se num1 è inferiore a num2 , valore positivo se num1 è maggiore di num2 e zero se entrambi sono uguali.

    Allo stesso modo, sortDescending() restituisce un valore negativo se num1 è maggiore di num2 , valore positivo se num2 è maggiore di num1 e zero se entrambi sono uguali.

  3. Dichiara un'altra funzione per ordinare l'array con il prototipo void sort(int * arr, int size, int (* compare)(int *, int *)) .

    Richiede tre parametri, dove il primo parametro è l'array da ordinare, il secondo è la dimensione dell'array e il terzo è un puntatore a funzione.

    Nota: Il puntatore alla funzione passato qui deciderà la relazione tra due elementi da ordinare. Se vuoi ordinare gli elementi in ordine crescente, passa il riferimento di sortAscending() funzione, altrimenti sortDescending() funzione.

    Per ordinare un array ho usato l'algoritmo di ordinamento di base. L'algoritmo non è efficiente rispetto ad altri algoritmi di ordinamento moderni, ma è facile da capire e da usare.

Programma per ordinare un array usando i puntatori

/**
 * C program to sort an array using pointers.
 */

#include <stdio.h>

#define MAX_SIZE 100


/* Function declaration */
void inputArray(int * arr, int size);
void printArray(int * arr, int size);

/* Sort function declaration */
int sortAscending(int * num1, int * num2);
int sortDescending(int * num1, int * num2);

void sort(int * arr, int size, int (* compare)(int *, int *));



int main()
{
    int arr[MAX_SIZE];
    int size;

    /*
     * Input array size and elements.
     */
    printf("Enter array size: ");
    scanf("%d", &size);
    printf("Enter elements in array: ");
    inputArray(arr, size);


    printf("\n\nElements before sorting: ");
    printArray(arr, size);


    // Sort and print sorted array in ascending order.
    printf("\n\nArray in ascending order: ");
    sort(arr, size, sortAscending);
    printArray(arr, size);


    // Sort and print sorted array in descending order.
    printf("\nArray in descending order: ");
    sort(arr, size, sortDescending);
    printArray(arr, size);

    
    return 0;
}



/**
 * Function to take input in array elements.
 * 
 * @arr     Array to store input.
 * @size    Size of the array.
 */
void inputArray(int * arr, int size)
{
    // Pointer to last element of array
    int * arrEnd = (arr + size - 1);


    // (arr++) Input in current array element and move to next element.
    // Till last array element (arr <= arrEnd)
    while(arr <= arrEnd)
        scanf("%d", arr++);
}




/**
 * Function to print all array elements.
 * 
 * @arr     Array to print.
 * @size    Size of the array.
 */
void printArray(int * arr, int size)
{
    // Pointer to last element of array
    int * arrEnd = (arr + size - 1);


    // *(arr++) Print current array element and move to next element.
    // Till last array element (arr <= arrEnd)
    while(arr <= arrEnd)
        printf("%d, ", *(arr++));
}



/**
 * Function to compare two succesive elements.
 * The function returns difference of first and second integer.
 * 
 * @num1    First integer to compare.
 * @num2    Second integer to compare.
 *
 * @return  Difference of num1 and num2.
 */
int sortAscending(int * num1, int * num2)
{
    return (*num1) - (*num2);
}



/**
 * Function to compare two successive elements. 
 * The function returns difference of second and first parameter.
 *
 * @num1    First integer to compare.
 * @num2    Second integer to compare.
 *
 * @return  Difference of num2 and num1.  
 */
int sortDescending(int * num1, int * num2)
{
    return (*num2) - (*num1);
}



/**
 * Function to sort an array in ascending or descending order.
 * This function is used to sort array in both order ascending or
 * descending.
 *
 * @arr     Array to sort.
 * @size    Size of the array.
 * @compare Function pointer returning integer and takes two int * 
 *          parameter. The function is called to get arrangement of
 *          two successive array elements.
 */
void sort(int * arr, int size, int (* compare)(int *, int *))
{
    // Pointer to last array element
    int * arrEnd  = (arr + size - 1);

    // Pointer to current array element
    int * curElem = arr;
    int * elemToSort;


    // Iterate over each array element
    while(curElem <= arrEnd)
    {
        elemToSort = curElem;


        // Compare each successive elements with current element
        // for proper order.
        while(elemToSort <= arrEnd)
        {
            /*
             * Compare if elements are arranged in order 
             * or not. If elements are not arranged in order
             * then swap them.
             */
            if(compare(curElem, elemToSort) > 0)
            {
                *curElem    ^= *elemToSort;
                *elemToSort ^= *curElem;
                *curElem    ^= *elemToSort;
            }

            elemToSort++;
        }

        // Move current element to next element in array.
        curElem++;
    }
}

Uscita

Enter array size: 10
Enter elements in array: 10 -1 0 4 2 100 15 20 24 -5


Elements before sorting: 10, -1, 0, 4, 2, 100, 15, 20, 24, -5,

Array in ascending order: -5, -1, 0, 2, 4, 10, 15, 20, 24, 100,
Array in descending order: 100, 24, 20, 15, 10, 4, 2, 0, -1, -5,

Post consigliati

  • Indice esercizi di programmazione di array e matrici.
  • Programma C per scambiare due numeri usando i puntatori.
  • Programma C per inserire e stampare elementi di array usando i puntatori.
  • Programma C per copiare un array in un altro usando i puntatori.
  • Programma C per scambiare due array usando i puntatori.
  • Programma C per invertire l'array usando i puntatori.
  • Programma C per cercare un elemento nell'array usando i puntatori.