In: Computer Science
Write program that pass unsorted one dimensional array
and a key to function,
the function will search for the key(using linear search) and if it
is found the
function will sort the array from the beginning to the position of
the key, and f
it is not found the function will sort all the array
Note: please solve it by c , not c++
Please find the program below in C language:
#include<stdio.h>
//Function to swap the value of two variables
void swap(int* first, int* second)
{
int temp = *first;
*first = *second;
*second = temp;
}
// Function to perform Selection Sort
void selectionSort(int array[], int no)
{
int i, j, min;
for (i = 0; i < no - 1; i++) {
// Find the minimum element in unsorted array
min = i;
for (j = i + 1; j < no; j++)
if (array[j] < array[min])
min = j;
// Swap the found minimum element with the first element
swap(&array[min], &array[i]);
}
}
// Function to implement search operation
int findElement(int array[], int no, int key)
{
int i;
for (i = 0; i < no; i++)
if (array[i] == key)
return i;
return -1;
}
// Function to print an array
void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
// Driver Code
int main()
{
int arr[] = {12, 34, 10, 6, 40}; /*Array elements. You can change
these values according to your requirement*/
int n = sizeof(arr) / sizeof(arr[0]);
int key, position;
printf("Enter the key value you want to search: ");
scanf("%d",&key); //Take input of the key value you want to
search
position = findElement(arr, n, key); //To find if the key value is
present in array
if (position == - 1) //If key value is not found
selectionSort(arr,n); //Sort the full array
else //If key value is found
selectionSort(arr,position+1); //Sort the array upto the position
of key value
printArray(arr,n); //Print the array
return 0;
}
Snapshot of the code output:
1. When the key value is present in the array:
2. When the key value is not present in the array: