Write a program that will randomly generate 1000 uppercase letters. Write those alphabets in a text file
named “in.txt”. Now Sort (in ascending order) all the alphabets in the file “in.txt” using insertion sort. Use
separate function for REPLACEMENT_SORT. Show the sorted output in your console window.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void REPLACEMENT_SORT(char uppercaseLetters[]){
int n = 1000;
int i;
for(i = 1; i < n; i++) {
int key = uppercaseLetters[i];
int j = i - 1;
//shift until you find the position to place the element 'key'
while(j >= 0 && uppercaseLetters[j] > key) {
uppercaseLetters[j+1] = uppercaseLetters[j];
j--;
}
//place element 'key' in the correct position in the sorted part of the array
uppercaseLetters[j+1] = key;
}
}
int main() {
char uppercaseLetters[1000];
int i;
FILE *fileSaveAlphabets;
FILE *fileReadAlphabets;
fileSaveAlphabets = fopen("in.txt", "w+");
srand(time(0));
//Write alphabets in a text file named "in.txt".
for (i = 0; i < 1000; i++){
fprintf(fileSaveAlphabets,"%c",(90 - (rand() % 26)),' ');
}
fclose(fileSaveAlphabets);
//Read uppercase letters from the file
i=0;
fileReadAlphabets = fopen("in.txt", "r");
if(fileReadAlphabets != NULL){
while(fscanf(fileReadAlphabets, "%c",&uppercaseLetters[i]) != EOF){
i++;
}
}
fclose(fileReadAlphabets);
REPLACEMENT_SORT(uppercaseLetters);
//Show the sorted output in your console window.
for (i = 0; i < 1000; i++){
printf("%c ",uppercaseLetters[i]);
}
getchar();
getchar();
return 0;
}
Comments
Leave a comment