0% found this document useful (0 votes)
2 views

Optimized_C_Program_Codes

Data structure using c codes

Uploaded by

khaparderahil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Optimized_C_Program_Codes

Data structure using c codes

Uploaded by

khaparderahil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Optimized and Shortened C Program Codes

1. Linear Search:

#include<stdio.h>

int linearSearch(int arr[], int n, int target) {

for(int i = 0; i < n; i++)

if(arr[i] == target) return i;

return -1;

int main() {

int arr[] = {10, 20, 30, 40, 50};

int n = sizeof(arr) / sizeof(arr[0]);

int target = 30;

int res = linearSearch(arr, n, target);

printf(res != -1 ? "Found at index: %d\n" : "Not found\n", res);

return 0;

2. Bubble Sort:

#include<stdio.h>

void bubbleSort(int arr[], int n) {

for(int i = 0; i < n-1; i++)

for(int j = 0; j < n-i-1; j++)

if(arr[j] > arr[j+1]) {

int temp = arr[j];

arr[j] = arr[j+1];
arr[j+1] = temp;

void printArray(int arr[], int n) {

for(int i = 0; i < n; i++) printf("%d ", arr[i]);

printf("\n");

int main() {

int arr[] = {64, 34, 25, 12, 22};

int n = sizeof(arr) / sizeof(arr[0]);

bubbleSort(arr, n);

printArray(arr, n);

return 0;

3. Selection Sort:

#include<stdio.h>

void selectionSort(int arr[], int n) {

for(int i = 0; i < n-1; i++) {

int min = i;

for(int j = i+1; j < n; j++)

if(arr[j] < arr[min]) min = j;

int temp = arr[min];

arr[min] = arr[i];

arr[i] = temp;

}
void printArray(int arr[], int n) {

for(int i = 0; i < n; i++) printf("%d ", arr[i]);

printf("\n");

int main() {

int arr[] = {29, 10, 14, 37, 13};

int n = sizeof(arr) / sizeof(arr[0]);

selectionSort(arr, n);

printArray(arr, n);

return 0;

4. Insertion Sort:

#include<stdio.h>

void insertionSort(int arr[], int n) {

for(int i = 1; i < n; i++) {

int key = arr[i], j = i - 1;

while(j >= 0 && arr[j] > key)

arr[j + 1] = arr[j--];

arr[j + 1] = key;

void printArray(int arr[], int n) {

for(int i = 0; i < n; i++) printf("%d ", arr[i]);

printf("\n");

int main() {
int arr[] = {5, 3, 8, 6, 2};

int n = sizeof(arr) / sizeof(arr[0]);

insertionSort(arr, n);

printArray(arr, n);

return 0;

You might also like