Homework problem that I am seriously stuck on, thank you in advance! This is C P
ID: 3539630 • Letter: H
Question
Homework problem that I am seriously stuck on, thank you in advance!
This is C Progamming:
a. Write a function to generate 100 unique random numbers in the range from 0 to 999. The function shall return the numbers through an output parameter.
b. Write a function to save the content of an array of numbers to a file, 10 numbers per line.
b. Rewrite the straight selection sort function from Chapter 8 using pointer arithmetic. Test your function with an array of 100 unique random numbers in the range from 0 to 999. Display the array 10 numbers per line before and after the sort.
Preferably my instructor said he wants this format:
Explanation / Answer
#include<stdio.h>
#include<stdlib.h>
#define SIZE 100
int buildList(int list[], int size);
int insertionSort(int list[], int size);
int printList(int list[], int size);
int main()
{
int arr[SIZE];
buildList(arr, SIZE);
printf("Array before sorting: ");
printList(arr, SIZE);
printf(" ");
insertionSort(arr, SIZE);
printf("Array after sorting: ");
printList(arr, SIZE);
printf(" ");
}
/*
Purpose: generate 100 distinct numbers between 0 to 999
Precondition: array list[] for storing numbers, int size : size of list[]
Postcondition: return 0 after completion
*/
int buildList(int list[], int size)
{
int arr[1000],i;
for(i=0;i<1000;i++)
arr[i] = 0;
int count = 0;
while(count<size)
{
int n = rand()%1000;
if(arr[n]==0)
{
arr[n]=1;
list[count] = n;
count++;
}
}
return 0;
}
/*
Purpose: sort elements using selection sort
Precondition: list[] : array of numbers , size : size of list[]
Postcondition: return 0 after completion
*/
int insertionSort(int list[], int size)
{
int i,j,temp;
for(i=0;i<size;i++)
for(j=i+1;j<size;j++)
{
if(*(list+i)>*(list+j))
{
temp=*(list+j);
*(list+j)=*(list+i);
*(list+i)=temp;
}
}
return 0;
}
/*
Purpose: print the elements of list
Precondition: list[] : array of numbers , size : size of list[]
Postcondition: return 0 after completion
*/
int printList(int list[], int size)
{
int i;
for(i=0;i<size;i++)
{
if(i>0&&i%10==0)
{
printf(" ");
}
printf("%d ",list[i]);
}
printf(" ");
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.