Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.8 kB
1
Indexable
Never
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#define MAX_ARRAY_SIZE 15

void generate_random_array(int *array, char **words, int size)
{
    srand(time(NULL)); // Seed the random number generator with the current time

    // Generate random numbers and words
    for (int i = 0; i < size; i++) {
        array[i] = rand() % 100;
        char *word = (char *) malloc(sizeof(char) * 6); // Allocate memory for a 5-letter word
        for (int j = 0; j < 5; j++) {
            word[j] = 'a' + rand() % 26; // Generate a random lowercase letter
        }
        word[5] = '\0'; // Add null terminator to the end of the word
        words[i] = word;
    }
}

void sort_array(int *array, char **words, int size)
{
    // Sort the array using binary search with pointers
    for (int i = 0; i < size; i++) {
        int key = array[i];
        char *key_word = words[i];
        int j = i - 1;
        while (j >= 0 && array[j] > key) {
            array[j + 1] = array[j];
            words[j + 1] = words[j];
            j--;
        }
        array[j + 1] = key;
        words[j + 1] = key_word;
    }
}

int main()
{
    int size = rand() % MAX_ARRAY_SIZE + 1; // Generate a random size for the array between 1 and MAX_ARRAY_SIZE
    int array[size];
    char *words[size];

    generate_random_array(array, words, size);

    printf("Before sorting:\n");
    for (int i = 0; i < size; i++) {
        printf("%d %s\n", array[i], words[i]);
    }

    sort_array(array, words, size);

    printf("After sorting:\n");
    for (int i = 0; i < size; i++) {
        printf("%d %s\n", array[i], words[i]);
    }

    // Free memory allocated for words
    for (int i = 0; i < size; i++) {
        free(words[i]);
    }

    return 0;
}