Sorting and Searching
Sorting
Sorting is used to speed up searching in a list of objects.
There are two types of sorting : Ascending and Descending.
Methods of sorting :
Bubble Sort
Bubble sort compares a variable with their neighbour and swap them if necessary.
Example :
void bubbleSort(int arr[], int n){
int i, j, temp;
for(i = 1; i < n; i++){
for(j = n - 1; j >= i; j--){
if(arr[j-1] > arr[j]){
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = arr[j-1];
}
}
}
Selection Sort
for(i = 0; i < n - 1; i++){
temp = i;
for(j = i+1; j < n; j++){
if(arr[j] < arr[temp]){
temp = j;
}
arr[i] = arr[temp];
}
Insertion Sort
for(i = 1; i < n; i++){
temp = arr[i];
for(j = 0; j <= i - 1; j++){
if(temp <= arr[j]){
temp1 = arr[j];
arr[j] = temp;
arr[i] = temp1;
}
}
Searching
Searching is an action to retrieve information based on a particular key.
Key is used to differentiate between data, therefore it must be unique.
Example : key for student is NIM.
Types of searching :
Linear Search
Linear searching compares the key to every elements in an array.
It works with small array and unsorted array.
Binary Search
Binary Search find the middle of the array first then looks if the key is in the left or the right.
It then repeated the action until it finds the desired data. The array must be sorted first before using binary search.
Sorting
Sorting is used to speed up searching in a list of objects.
There are two types of sorting : Ascending and Descending.
Methods of sorting :
Bubble Sort
Bubble sort compares a variable with their neighbour and swap them if necessary.
Example :
void bubbleSort(int arr[], int n){
int i, j, temp;
for(i = 1; i < n; i++){
for(j = n - 1; j >= i; j--){
if(arr[j-1] > arr[j]){
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = arr[j-1];
}
}
}
Selection Sort
for(i = 0; i < n - 1; i++){
temp = i;
for(j = i+1; j < n; j++){
if(arr[j] < arr[temp]){
temp = j;
}
arr[i] = arr[temp];
}
Insertion Sort
for(i = 1; i < n; i++){
temp = arr[i];
for(j = 0; j <= i - 1; j++){
if(temp <= arr[j]){
temp1 = arr[j];
arr[j] = temp;
arr[i] = temp1;
}
}
Searching
Searching is an action to retrieve information based on a particular key.
Key is used to differentiate between data, therefore it must be unique.
Example : key for student is NIM.
Types of searching :
Linear Search
Linear searching compares the key to every elements in an array.
It works with small array and unsorted array.
Binary Search
Binary Search find the middle of the array first then looks if the key is in the left or the right.
It then repeated the action until it finds the desired data. The array must be sorted first before using binary search.
Comments
Post a Comment