Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Advanced Algorithms & Data Structures: Lecturer: Karimzhan Nurlan Berlibekuly

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 23

ADVANCED

ALGORITHMS &
DATA STRUCTURES
Lecture-01
Arrays and Pointer Arrays
Sort Algorithms: Selection Sort, Bubble Sort
Medians and order statistics

Lecturer: Karimzhan Nurlan Berlibekuly


nkarimzhan@gmail.com
Arrays
An array is collection of items stored at contiguous
memory locations.
The idea is to store multiple items of same type together.
This makes it easier to calculate the position of each
element by simply adding an offset to a base value, i.e.,
the memory location of the first element of the array
(generally denoted by the name of the array).
Arrays

Advantages of using arrays:


•Arrays allow random access of elements. This makes accessing elements by
position faster.
•Arrays have better cache locality that can make a pretty big difference in
performance.
Arrays – Examples:
// A character array in C/C++/Java
char arr1[] = {'g', 'e', 'e', 'k', 's'};

// An Integer array in C/C++/Java


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

// Item at i'th index in array is typically accessed


// as "arr[i]". For example arr1[0] gives us 'g'
// and arr2[3] gives us 40.
Pointer Arrays
Pointers store address of variables or a
memory location.

// General syntax
datatype *var_name;

// An example pointer "ptr" that holds


// address of an integer variable or holds
// address of a memory whose value(s) can
// be accessed as integer values through "ptr"
int *ptr;
Pointer Arrays – Using a Pointer
Pointer Arrays – Using a Pointer
To use pointers in C, we must understand
below two operators.
- To access address of a variable to a pointer, we use the unary
operator & (ampersand) that returns the address of that variable. For example
&x gives us address of variable x.
- One more operator is unary * (Asterisk) which is used for two things :
To declare a pointer variable: When a pointer variable is declared in C/C++,
there must a * before its name.
- To access the value stored in the address we use the unary operator (*) that
returns the value of the variable located at the address specified by its
operand.
Pointer Expressions and Arithmetic
A limited set of arithmetic operations can be performed on pointers. A pointer
may be:

•incremented ( ++ )
•decremented ( — )
•an integer may be added to a pointer ( + or += )
•an integer may be subtracted from a pointer ( – or -= )

Pointer arithmetic is meaningless unless performed on an array.

Note : Pointers contain addresses. Adding two addresses makes no sense,


because there is no idea what it would point to. Subtracting two addresses lets
you compute the offset between these two addresses.
Pointer: Array Name as Pointers
An array name acts like a pointer constant. The value of this pointer constant is the
address of the first element.
For example, if we have an array named val then val and &val[0] can be used
interchangeably.
// C++ program to illustrate Array Name as ptr = val ;
Pointers in C++ cout << "Elements of the array are: ";
#include <bits/stdc++.h> cout << ptr[0] << " " << ptr[1] << " " <<
using namespace std; ptr[2];

void geeks() return;


{ }
// Declare an array
int val[3] = { 5, 10, 15}; // Driver program
int main()
// Declare pointer variable {
int *ptr; geeks();
return 0;
// Assign address of val[0] to ptr. }
// We can use ptr=&val[0];(both are same)

Now if this ptr is sent to a function as an argument then the array


Output: Elements of the array are: 5 10 15 val can be accessed in a similar fashion.
Pointers and Multidimensional
Arrays
You can use pointer arithmetic to access any element in any array in
C, including multi-dimensional arrays. Two-dimensional arrays in C
are stored in row-major order. In a two-dimensional array, the
memory location of the element at [row][col] is:
p + (num_cols * row) + col
where p is the address of the first element in the array (at [0][0]),
“num_cols” is the number of columns in the array, row is the row
index of the entry and col is the column index of the entry.
For example, given the array definition “int array[3][5]”, the
equation &array[0][0] + (5 * 2) + 1 indexes the element at array[2]
[1].
Pointers and Multidimensional
Arrays
#include <stdio.h> COLS = 4,
TOTAL_CELLS = ROWS * COLS,
int main(void) { i;
// print the elements of the array num via
// 2d array pointer ptr
int num[3][4] = { for (i = 0; i < TOTAL_CELLS; i++) {
{1, 2, 3, 4}, printf("%d ", *(ptr + i));
{5, 6, 7, 8}, }
{9, 10, 11, 12}
}; //p + (num_cols * row) + col

// pointer ptr pointing at array num // printf num[1][2]


int *ptr = &num[0][0]; printf("\n");

// other variables printf("%d ", *(ptr + (COLS * 1) + 2));


int
ROWS = 3, return 0;
}
Selection Sort
The selection sort algorithm sorts an array by repeatedly finding the minimum
element (considering ascending order) from unsorted part and putting it at the
beginning. The algorithm maintains two subarrays in a given array.
1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.
In every iteration of selection sort, the minimum element (considering ascending
order) from the unsorted subarray is picked and moved to the sorted subarray.
Selection Sort Following example explains the above
steps:
Selection Sort
// Java program for implementation of Selection Sort // Prints the array
class SelectionSort void printArray(int arr[])
{ {
void sort(int arr[]) int n = arr.length;
{ for (int i=0; i<n; ++i)
int n = arr.length; System.out.print(arr[i]+" ");
System.out.println();
// One by one move boundary of unsorted }
subarray
for (int i = 0; i < n-1; i++) // Driver code to test above
{ public static void main(String args[])
// Find the minimum element in unsorted array {
int min_idx = i; SelectionSort ob = new SelectionSort();
for (int j = i+1; j < n; j++) int arr[] = {64,25,12,22,11};
if (arr[j] < arr[min_idx]) ob.sort(arr);
min_idx = j; System.out.println("Sorted array");
ob.printArray(arr);
}
// Swap the found minimum element with the first }
// element /* This code is contributed by Rajat Mishra*/
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp; Output:
} Sorted array:
} 11 12 22 25 64
Selection Sort
Time Complexity: O(n2) as there are two nested loops.
Auxiliary Space: O(1)
The good thing about selection sort is it never makes more than O(n) swaps
and can be useful when memory write is a costly operation.
Bubble Sort
Bubble Sort
// C program for implementation of /* Function to print an array */
Bubble sort void printArray(int arr[], int size)
#include <stdio.h> {
int i;
void swap(int *xp, int *yp) for (i=0; i < size; i++)
{ printf("%d ", arr[i]);
int temp = *xp; printf("\n");
*xp = *yp; }
*yp = temp;
} // Driver program to test above
functions
// A function to implement bubble sort int main()
void bubbleSort(int arr[], int n) {
{ int arr[] = {64, 34, 25, 12, 22, 11, 90};
int i, j; int n = sizeof(arr)/sizeof(arr[0]);
for (i = 0; i < n-1; i++) bubbleSort(arr, n);
printf("Sorted array: \n");
// Last i elements are already in printArray(arr, n);
place return 0;
for (j = 0; j < n-i-1; j++) }
if (arr[j] > arr[j+1]) Sorted array:
swap(&arr[j], &arr[j+1]); 11 12 22 25 34 64 90
}
Bubble Sort
Optimized Implementation:
The above function always runs O(n^2) time even if the array is sorted. It can
be optimized by stopping the algorithm if inner loop didn’t cause any swap.
Mean and median of an unsorted array
Mean of an array = (sum of all elements) /
(number of elements)

Median of a sorted array of size n is defined


as below :

It is middle element when n is odd and average


of middle two elements when n is even.

2, 5, 6, 9, 19, 20, 24
Median = 9
3, 4, 7, 10, 15, 20
Median = (7 + 10)/2 = 8,5
Since the array is not sorted here, we sort
the array first, then apply above formula.
Mean and median of an unsorted array
Average salary in country
50 000, 50 000, 50 000, 50 000, 50 000, 50 000, 1 000 000, 1 000 000

Mean = 287 500

Median = 50 000
Mean and median of an unsorted array
Input : a[] = {1, 3, 4, 2, 6, 5, 8, 7}
Output : Mean = 4.5
Median = 4.5
Sum of the elements is 1 + 3 + 4 + 2 + 6 +
5 + 8 + 7 = 36
Mean = 36/8 = 4.5

Since number of elements are even, median


is average of 4th and 5th largest elements.
which means (4 + 5)/2 = 4.5

Input : a[] = {4, 4, 4, 4, 4}


Output : Mean = 4
Median = 4
Order statistics
K’th Smallest/Largest Element in Unsorted Array

// Simple C++ program to find k'th smallest element Input: arr[] = {7, 10, 4, 3, 20, 15}
#include<iostream>
#include<algorithm>
k=3
using namespace std; Output: 7

// Function to return k'th smallest element in a given array Input: arr[] = {7, 10, 4, 3, 20, 15}
int kthSmallest(int arr[], int n, int k)
{ k=4
// Sort the given array Output: 10
sort(arr, arr+n);

// Return k'th element in the sorted array


return arr[k-1];
}

// Driver program to test above methods


int main()
{
int arr[] = {12, 3, 5, 7, 19};
int n = sizeof(arr)/sizeof(arr[0]), k = 2;
cout << "K'th smallest element is " << kthSmallest(arr, n, k);
return 0;
}
References
Packt. Java 9 Data Structures and Algorithms
Mark Allen Weiss - Data Structures and Algorithm Analysis in C++, 2014

Robert Sedgewick and Kevin Wayne - Algorithms, 4th edition, 2011


Peter Brass - Advanced Data Structures

https://www.geeksforgeeks.org
https://www.mathgoodies.com/lessons/vol8/median

https://www.dropbox.com/sh/37ktt7arr0vuoze/AADPwqRsy8lbHWbIRR5tVUnSa?dl=0

You might also like