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

Arrays and Sorting

The document provides an overview of arrays in programming, including their declaration, initialization, and access methods. It discusses one-dimensional and two-dimensional arrays, their advantages and disadvantages, and introduces string handling functions in C. Additionally, it covers various sorting algorithms such as QuickSort, Bubble Sort, Insertion Sort, and Selection Sort with example code for each.

Uploaded by

manitarora33
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Arrays and Sorting

The document provides an overview of arrays in programming, including their declaration, initialization, and access methods. It discusses one-dimensional and two-dimensional arrays, their advantages and disadvantages, and introduces string handling functions in C. Additionally, it covers various sorting algorithms such as QuickSort, Bubble Sort, Insertion Sort, and Selection Sort with example code for each.

Uploaded by

manitarora33
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Array is a data structure that stores a fixed-size, sequential collection of elements of the

same data type. Arrays are used to organize and manipulate collections of data efficiently.
In declaration, we specify then name and the size of the 1d array.
elements_type array_name[array_size];

Declaration and Initialization


An array is declared by specifying the data type of its elements, a name, and the number of
elements it will store within square brackets. Initialization can occur at the time of
declaration or later.
int numbers[5]; // Declares an integer array named 'numbers' with 5 elements
int scores[3] = {85, 92, 78}; // Declares and initializes an integer array

Accessing Elements
Array elements are accessed using their index, which starts from 0 for the first element.
int first_number = numbers[0]; // Accesses the first element
numbers[1] = 100; // Modifies the second element

EXAMPLE:
#include <stdio.h>

int main() {
int grades[5] = {90, 85, 78, 95, 88};
int sum = 0;

for (int i = 0; i < 5; i++) {


sum += grades[i];
}

float average = (float)sum / 5;


printf("Average grade: %.2f\n", average);
return 0;
}

Rules for Declaring a One Dimensional Array:


Before using an array variable in a program, it must be declared. We can do the declaration
by the below rules:
• A data type (int, float, char, double, etc.), variable name, and subscript must be
specified in the declaration.

• The subscript represents the array's size. For example, when the size is set to 10,
programmers can store ten elements.

• An array index always begins with 0. For example, if an array variable is declared
as array[10], the index can take values between 0 and 9.

• Each array element is kept in its memory location.

Arrays are used in various applications:


• Storing lists of data (e.g., student names, product prices).
• Implementing other data structures (e.g., stacks, queues).
• Performing matrix operations.
• Representing tables of data.
Advantages
• Efficient access to elements using indices.
• Simple and easy to use for storing collections of data.
• Contiguous memory allocation, which can improve performance in some cases.
Disadvantages
• Fixed size, which cannot be changed after declaration (unless using dynamic memory
allocation).
• Inserting or deleting elements in the middle of an array can be inefficient.
• Arrays can lead to out-of-bounds errors if not handled carefully.

A two-dimensional array is essentially an array of arrays, organized in rows and


columns, forming a table-like structure. It is declared using the syntax data_type
array_name[row_size][column_size];. Each element is accessed using two
indices: array_name[row_index][column_index], where row_index ranges from 0
to row_size - 1, and column_index ranges from 0 to column_size - 1.
Declaration of 2D Array
A 2D array with m rows and n columns can be created as:
type arr_name[m][n];
where,
• type: Type of data to be stored in each element.
• arr_name: Name assigned to the array.
• m: Number of rows.
• n: Number of columns.

A 2D array can be initialized during declaration using nested braces, or element-wise later in
the code. For example:
int matrix[3][3] = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

Array of Characters (Strings)


One popular use of an array is the 1D array of characters used to represent textual data. It is
more commonly known as strings. Strings are essentially an array of characters terminated
by a NULL character ('0').
Syntax
char name[] = "this is an example string"

The string handling functions are defined in the header file string.h. This header file must be
included in the C program to use the string handling functions.
The following are the string functions in C:

Function Description

strlen() It returns the string's length.

strcmp() It compares two strings and returns 0 if the strings are the same.

strcat() It concatenates two strings and returns the concatenated string.

strcpy() It copies one string into another.


Function Description

The strlwr() function takes a single string as its argument. The function is used to convert the
passed string into lowercase.

strlwr() Syntax
strlwr(string1);

The strupr() function takes a single string as its argument. The function is used to convert the
passed string into uppercase.
strupr()
Syntax
strupr(string1);

Advantages of String Functions in C


• Efficiency: String functions like strcpy, strcat, and strlen provide optimized and tested
ways to handle common string operations efficiently.
• Consistency: Using standard library functions ensures consistent behavior across
different implementations and platforms.
• Ease of Use: Functions simplify common tasks such as copying, concatenating, and
comparing strings, reducing the need for custom code.
• Memory Management: Functions handle memory allocation and deallocation,
reducing the risk of memory-related errors when working with strings.
Disadvantages of String Functions in C
• Safety Issues: Functions like strcpy and strcat are prone to buffer overflow if not used
carefully, leading to potential security vulnerabilities.
• Lack of Bounds Checking: Many string functions do not check for buffer overflows or
invalid access, requiring developers to manually ensure safe usage.
• Performance Overheads: Some functions may incur performance overhead due to
internal checks and operations, especially when dealing with large strings.
• Limited Flexibility: Functions are designed for specific operations and may not
handle all edge cases or complex string manipulations effectively.
QuickSort is to select a pivot element from the array and partition the other elements into
two sub-arrays according to whether they are less than or greater than the pivot. The sub-arrays are
then sorted recursively. This process of partitioning and sorting continues until the entire array is
sorted.
quick sort algorithm basically requires implementation of two functions:
1. partition() Function
2. quickSort() Function
The quicksort() function first calls the partition() function. The partition() function rearranges the
given subarray around the selected pivot such that all the elements less that pivot are placed left of it
and all the elements greater that pivot are placed right of the pivot. Finally, it returns the index of the
pivot to the quicksort.
Then quicksort() function divides the array into two subarrays based on this index and repeats the
process for these two subarrays. This will go on till the given subarray cannot be further divided. At
this point, the array is already sorted.

#include <stdio.h>
// Function to swap two elements
void swap(int* a, int* b) {
int t = *a;
*a = *b;
*b = t;
}

// Function to partition the array


int partition(int arr[], int low, int high) {
int pivot = arr[high]; // Choose the last element as the pivot
int i = (low - 1); // Index of smaller element

for (int j = low; j <= high - 1; j++) {


// If the current element is smaller than or equal to the pivot
if (arr[j] <= pivot) {
i++; // increment index of smaller element
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}

// Function to implement quicksort


void quickSort(int arr[], int low, int high) {
if (low < high) {
// pi is partitioning index, arr[pi] is now at right place
int pi = partition(arr, low, high);

// Recursively sort elements before partition and after partition


quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
// Function to print an array
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}
// Main function
int main() {
int arr[] = {10, 7, 8, 9, 1, 5};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Unsorted array: \n");
printArray(arr, n);
quickSort(arr, 0, n - 1);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}

OUTPUT:
[1, 5, 7, 8, 9, 10]
CODE FOR BUBBLE SORT:
#include <stdio.h>
// Function to perform Bubble Sort
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
// Last i elements are already in place
for (int j = 0; j < n - i - 1; j++) {
// Swap if elements are in wrong order
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
// Function to print an array
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}

// Main function
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n);
printf("Sorted array:\n");
printArray(arr, n);
return 0;
}
OUTPUT: Sorted array:
11 12 22 25 34 64 90

CODE FOR INSERTION SORT:


#include <math.h>
#include <stdio.h>

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

// Starting from the second element


for (int i = 1; i < N; i++) {
int key = arr[i];
int j = i - 1;

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


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

// Move the key to its correct position


arr[j + 1] = key;
}
}
int main() {
int arr[] = { 12, 11, 13, 5, 6 };
int N = sizeof(arr) / sizeof(arr[0]);
insertionSort(arr, N);

printf("Sorted array: ");


for (int i = 0; i < N; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}

OUTPUT: Sorted array: 5 6 11 12 13

CODE FOR SELECTION SORT:


#include <stdio.h>
void selectionSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {

// Assume the current position holds


// the minimum element
int min= i;

// Iterate through the unsorted portion


// to find the actual minimum
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[min]) {

// Update min if a smaller element is found


min = j;
}
}

// Move minimum element to its


// correct position
int temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
}
}
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}

int main() {
int arr[] = {20,12,10,15,2};
int n = sizeof(arr) / sizeof(arr[0]);
selectionSort(arr, n);
printf("Sorted array: ");
printArray(arr, n);

return 0;
}

You might also like