Sie sind auf Seite 1von 12

Bubble Sort is a simple algorithm which is

used to sort a given set of n elements Implementing Bubble Sort Algorithm


provided in form of an array with n number Following are the steps involved in bubble
of elements. Bubble Sort compares all the sort(for sorting a given array in ascending
element one by one and sort them based on order):
their values.

#include <stdio.h> 1. Starting with the first element(index =


void bubbleSort(int arr[], int n) 0), compare the current element with
{
the next element of the array.
int i, j, temp;
for(i = 0; i < n; i++) 2. If the current element is greater than
{ the next element of the array, swap
for(j = 0; j < n-i-1; j++)
{ them.
if( arr[j] > arr[j+1]) 3. If the current element is less than the
{
next element, move to the next
// swap the elements
temp = arr[j]; element. Repeat Step 1.
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
// print the sorted array
printf("Sorted Array: ");
for(i = 0; i < n; i++)
{
printf("%d ", arr[i]);
}
}
int main()
{
int arr[100], i, n, step, temp;
// ask user for number of elements to be
sorted
printf("Enter the number of elements to
be sorted: ");
scanf("%d", &n);
// input elements if the array
for(i = 0; i < n; i++)
{
printf("Enter element no. %d: ", i+1);
scanf("%d", &arr[i]);
}
// call the function bubbleSort
bubbleSort(arr, n);
return 0;
}

Insertion sort is a sorting algorithm in Following are the steps involved in insertion
which the elements are transferred one at a sort:
time to the right position. In other words,
1. insertionSort(array)
an insertion sort helps in building the
2. mark first element as sorted
final sorted list, one item at a time, with the
3. for each unsorted element X
movement of higher-ranked elements.
4. 'extract' the element X
import java.util.Arrays; 5. for j <- lastSortedIndex down to 0
6. if current element j > X
class InsertionSort { 7. move sorted element to the right by
void insertionSort(int array[]) { 1
int size = array.length; 8. break loop and insert X here
for (int step = 1; step < size; step++) { 9. end insertionSort
int key = array[step];
int j = step - 1;
while (j >= 0 && key < array[j]) {
// For descending order, change
key<array[j] to key>array[j].
array[j + 1] = array[j];
--j;
}
array[j + 1] = key;
}
}

public static void main(String args[]) {


int[] data = { 9, 5, 1, 4, 3 };
InsertionSort is = new InsertionSort();
is.insertionSort(data);
System.out.println("Sorted Array in
Ascending Order: ");
System.out.println(Arrays.toString(data));
}
}

Selection sort is conceptually the most Following are the steps involved in selection
sort(for sorting a given array in ascending
simplest sorting algorithm. This algorithm will
order):
first find the smallest element in the array
and swap it with the element in 1. Starting from the first element, we
the first position, then it will find the second search the smallest element in the
array, and replace it with the element
smallest element and swap it with the
in the first position.
element in the second position, and it will
2. We then move on to the second
keep on doing this until the entire array is
position, and look for smallest element
sorted. It is called selection sort because it
present in the subarray, starting from
repeatedly selects the next-smallest
index 1, till the last index.
element and swaps it into the right place.
3. We replace the element at
the second position in the original
array, or we can say at the first
# include <stdio.h>
position in the subarray, with the
// function to swap elements at the given second smallest element.
index values
4. This is repeated, until the array is
void swap(int arr[], int firstIndex, int
secondIndex) completely sorted.
{
int temp;
temp = arr[firstIndex];
arr[firstIndex] = arr[secondIndex];
arr[secondIndex] = temp;
}
// function to look for smallest element in the
given subarray
int indexOfMinimum(int arr[], int startIndex,
int n)
{
int minValue = arr[startIndex];
int minIndex = startIndex;

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


if(arr[i] < minValue)
{
minIndex = i;
minValue = arr[i];
}
}
return minIndex;
}

void selectionSort(int arr[], int n)


{
for(int i = 0; i < n; i++)
{
int index = indexOfMinimum(arr, i, n);
swap(arr, i, index);
}

void printArray(int arr[], int size)


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

int main()
{
int arr[] = {46, 52, 21, 22, 11};
int n = sizeof(arr)/sizeof(arr[0]);
selectionSort(arr, n);
printf("Sorted array: \n");
printArray(arr, n);
return 0;
}

MergeSort is the Divide and Conquer 1. Divide: In this step, we divide an


algorithm. It divides input array into two input array into 2 halves, the pivot
halves, calls itself for the two halves and being the midpoint of an array. This
then merges that two sorted halves. The step is carried out recursively for all the
merge() function is used for merging the half arrays until there are no more half
two halves. In one sentence, we can say, in arrays to divide.
Merge Sort, we perform Divide Operation, 2. Conquer: In this step, we sort and
then Conquer and Combine Operation. merge a divided array from a bottom
to top and get the sorted array.

import java.util.*;

public class MergeSort {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the
Array: ");
int size_of_arry = sc.nextInt(); // size of
array, to b entered by the user
int arr[] = new int[size_of_arry];
System.out.println("Enter Array Elements
");
for (int i = 0; i < size_of_arry; i++)
arr[i] = sc.nextInt(); // element of array,
to be entered by the user
arr = Merge_sort(arr, size_of_arry);
System.out.println("Array after Merge
Sort is: ");
for (int i = 0; i < size_of_arry; i++)
System.out.print(arr[i] + " ");
System.out.println("\n");
}
static int[] Merge_sort(int arr[], int size) {
if (size > 1) {
int mid = size / 2;
int[] first = Arrays.copyOfRange(arr, 0,
mid);
first = Merge_sort(first, mid); // recursive
call for first half array
int[] second = Arrays.copyOfRange(arr,
mid, size);
second = Merge_sort(second, size -
mid); // recursive call for second half array
arr = Merge_arrays(first, second, mid,
size - mid);
}
return arr;
}
static int[] Merge_arrays(int first[], int
second[], int n, int m) // respectively
{
int arr[] = new int[n + m];
int i = 0, f = 0, s = 0;
while (f < n && s < m) {
if (first[f] < second[s])
arr[i++] = first[f++];
else
arr[i++] = second[s++];
}
while (f < n)
arr[i++] = first[f++];
while (s < m)
arr[i++] = second[s++];
return arr;
}
}

Quicksort is a divide and conquer algorithm. It first divides a large list into
two smaller sub-lists and then recursively sort the two sub-lists. If we want
to sort an array without any extra space, quicksort is a good option. On
average, time complexity is O(n log(n)).
Quicksort is a popular sorting algorithm that is often faster in practice
compared to other sorting algorithms. It utilizes a divide-and-conquer
strategy to quickly sort data items by dividing a large array into two smaller
arrays.

public class JavaApplication257 {


public static void quickSort(int[] array) {
for(int j=0; j<array.length-1;j++){

int max=j;

for(int K=j+1;K<array.length;K++)
if(array[K]<array[max])max=K;

int temp=array[j];
array[j]=array[max];
array[max]=temp;

}
}
public static void main(String[] args){
int[] values ={-11,-8,9,1,3,8,-10,-15};

System.out.println("Original Array");
for(int val:values)
System.out.print(val+",");

quickSort(values);
System.out.println();
System.out.println("Sorted Array:");
for(int val: values)
System.out.print(val+",");
System.out.println();
}
}
Module 3
Search operation
class Main
{
// Function to implement
// search operation
static int findElement(int arr[], int n,
int key)
{
for (int i = 0; i < n; i++)
if (arr[i] == key)
return i;

return -1;
}

// Driver Code
public static void main(String args[])
{
int arr[] = {12, 34, 10, 6, 40};
int n = arr.length;

// Using a last element as search element


int key = 40;
int position = findElement(arr, n, key);

if (position == - 1)
System.out.println("Element not found");
else
System.out.println("Element Found at Position: "
+ (position + 1));
}
}

Output :
Element found at position 5

Deletion operation
class Main
{
// function to search a key to
// be deleted
static int findElement(int arr[], int n, int key)
{
int i;
for (i = 0; i < n; i++)
if (arr[i] == key)
return i;

return -1;
}

// Function to delete an element


static int deleteElement(int arr[], int n, int key)
{
// Find position of element to be
// deleted
int pos = findElement(arr, n, key);

if (pos == -1)
{
System.out.println("Element not found");
return n;
}

// Deleting element
int i;
for (i = pos; i< n - 1; i++)
arr[i] = arr[i + 1];

return n - 1;
}

// Driver Code
public static void main(String args[])
{
int i;
int arr[] = {10, 50, 30, 40, 20};

int n = arr.length;
int key = 30;

System.out.println("Array before deletion");


for (i=0; i<n; i++)
System.out.print(arr[i] + " ");

n = deleteElement(arr, n, key);
System.out.println("\n\nArray after deletion");
for (i=0; i<n; i++)
System.out.print(arr[i]+" ");
}
}

Output :
Array before deletion
10 50 30 40 20
Array after deletion
10 50 40 20

Insertion operation
class Main
{
// Function to insert a given key in
// the array. This function returns n+1
// if insertion is successful, else n.
static int insertSorted(int arr[], int n,
int key,
int capacity)
{

// Cannot insert more elements if n


// is already more than or equal to
// capcity
if (n >= capacity)
return n;

arr[n] = key;

return (n + 1);
}

// Driver Code
public static void main (String[] args)
{
int[] arr = new int[20];
arr[0] = 12;
arr[1] = 16;
arr[2] = 20;
arr[3] = 40;
arr[4] = 50;
arr[5] = 70;
int capacity = 20;
int n = 6;
int i, key = 26;

System.out.print("Before Insertion: ");


for (i = 0; i < n; i++)
System.out.print(arr[i]+" ");

// Inserting key
n = insertSorted(arr, n, key, capacity);

System.out.print("\n After Insertion: ");


for (i = 0; i < n; i++)
System.out.print(arr[i]+" ");
}
}

Output:
Before Insertion: 12 16 20 40 50 70
After Insertion: 12 16 20 40 50 70 26

Das könnte Ihnen auch gefallen