You are on page 1of 24

C code for Insertion Sort

Posted by Saurabh on July 17th, 2010

Writing programs for sorting of a given set of numbers is one of the common programming tasks. Various types of sorting techniques like selection sort, inserting sort and quick sort are quite popular. Here C code for Insertion sort is being presented. The program is quite simple. Here, in each iteration, the elements are placed in their correct position. The algorithm has the complexity of O(n) #include "stdio.h" void main( ) { int arr[5] = { 25, 17, 31, 13, 2 } ; int i, j, k, temp ; printf ( "Insertion sort.\n" ) ; printf ( "\nArray before sorting:\n") ; for ( i = 0 ; i <= 4 ; i++ ) printf ( "%d\t", arr[i] ) ; for ( i = 1 ; i <= 4 ; i++ ) { for ( j = 0 ; j < i ; j++ ) { if ( arr[j] > arr[i] ) { temp = arr[j] ; arr[j] = arr[i] ; for ( k = i ; k > j ; k-- ) arr[k] = arr[k - 1] ; arr[k + 1] = temp ; } } printf ( "\n\nArray after sorting:\n") ; for ( i = 0 ; i <= 4 ; i++ ) printf ( "%d\t", arr[i] ) ; } }

C Code for Bubble Sort


Posted by Saurabh on July 19th, 2010

Searching and sorting have been popular operations in elementry data structures. Although now a days many advanced sorting techniques are used to sort a set of data, the basic sorting methods are still popular and are the used frequently. Here C code for bubble sort is given. The algorithm for bubble sort is quite simple. In each iteration the adjacent elements are compared and they are swapped if their order is not correct. The complexity of this algorithm comes out to be O(n). The C code is as follows : #include "stdio.h" #include "conio.h" void main( ) { int arr[5] = { 25, 17, 31, 13, 2 } ; int i, j, temp ; for ( i = 0 ; i <= 3 ; i++ ) { for ( j = 0 ; j <= 3 - i ; j++ ) { if ( arr[j] > arr[j + 1] ) { temp = arr[j] ; arr[j] = arr[j + 1] ; arr[j + 1] = temp ; } } } printf ( "\n\nArray after sorting:\n") ; for ( i = 0 ; i <= 4 ; i++ ) printf ( "%d\t", arr[i] ) ; }

C Code for Selection Sort


Posted by Saurabh on July 18th, 2010

Searching and sorting have been popular operations in elementry data structures. Although now a days many advanced sorting techniques are used to sort a set of data, the basic sorting methods are still popular and are the used frequently. Here C code for selection sort is given. The algorithm for selection sort is quite simple. In the first iteration, 1st element is compared against all the other elements (from array index 1 to array index n). In the second iteration 2nd element is compared with the elements from array index 2 to n. This process is repeated n-1 times. The C code is as follows : #include "stdio.h"

void main( ) { int arr[5] = { 25, 17, 31, 13, 2 } ; int i, j, temp ; for ( i = 0 ; i <= 3 ; i++ ) { for ( j = i + 1 ; j <= 4 ; j++ ) { if ( arr[i] > arr[j] ) { temp = arr[i] ; arr[i] = arr[j] ; arr[j] = temp ; } } } printf ( "\n\nArray after sorting:\n") ; for ( i = 0 ; i <= 4 ; i++ ) printf ( "%d\t", arr[i] ) ; }

Java code for shuffling


Posted by Saurabh on October 27th, 2010

Many times we are required to shuffle a particular set of objects so that they may mix up properly. A standard way to shuffle any set of objects is to swap their positions randomly. The code given below does this by swapping the position of all the numbers of the array. The code uses the Random utility of utils class for generating random numbers. Random obj = new Random(); int[] items = new int[10]; int randomPosition; for (int i=0; i<items.length; i++) { items[i] = i; } //--- Shuffle by exchanging each element randomly for (int i=0; i<tems.length; i++) { randomPosition = obj.nextInt(items.length); int temp = items[i]; items[i] = items[randomPosition]; items[randomPosition] = temp; }

Java Code for generating Unique Random Numbers


Posted by Saurabh on January 31st, 2011

Generating Random Numbers is quite simple. Just use the class Random and method nextInt as : new Random().nextInt(10); This will generate a unique random number between 0 and 9 (both inclusive). Similarly if you want to generate a unique random number between a fixed length, say 10 to 100, use can use a code something like : new Random().nextInt(90)+11; However, while developing games or implementing Artificial Intelligence, we often require an efficient algorithm or piece of code which can generate unique random numbers within a given range. The logic behind this is pretty simple. Take a for loop and insert all the numbers which you want to be called randomly in an ArrayList, shuffle the ArrayList and extract the numbers one by one. The java code for this is presented below : public class RandomNumberGenerator { ArrayList numbersList = new ArrayList (); public RandomNumberGenerator(int length) { for(int x=1;x<=length;x++) numbersList.add(x); Collections.shuffle(numbersList); } public int generateNewRandom(int n) { return numbersList.get(n); } } Now you can use this class for generation of unique random numbers in your program. Just pass the required arguement in the constructor and then use the method generateNewRandom()

! TECHNICALSYMPOS IUM.COM!
Short-term Course Details

know the personalities hold your mouse,move left and right

Home University Symposiums College Symposiums IIT Symposiums IIM Symposiums IIIT Symposiums NIT Symposiums Gallery

C Program For BINARY SEARCH.

Search

Freshers Jobs/Events/Certification(s) &Education News Given Below-Forward to all Friends

All types of Govt/Soft ware/IT Jobs are Given Below


Know More here

All Departm ents of National/Internation Engineer Software/Aptit ing ude/Tech al Question Symposium,Confer Lecture Notes Papers are ence,Workshop are Given Below Details given below given Know More here Know More here below
Know More here

C/C+ +/JAVA/Ap ti Questions and Lab Codings are Given Below


Know More

Training Info Admissions Info Courses Info Scholarships Info

GATE Info UPSC Info Job Info Materials Info

C Program For BINARY SEARCH. #include<stdio.h> #include<conio.h> void main() { int n,i,search,f=0,low,high,mid,a[20]; clrscr(); printf("Enter the n value:"); scanf("%d",&n); for(i=1;i<=n;i++) { printf("Enter the number in ascending order a[%d]=",i); scanf("%d",&a[i]); } printf("Enter the search element:"); scanf("%d",&search); low=1; high=n; while(low<=high) { mid=(low+high)/2; if(search<a[mid]) { high=mid-1; } else if(search>a[mid]) { low=mid+1; } else { f=1; printf("obtainedin the position %d:",mid); getch(); exit();

} } if(f==0) { printf("not present"); } getch(); }

b=a+b a=b-a b=b-a if a=3 and b=5 then now b=a+b=8 and a=8-a=8-3=5,now a=5 b=8-a=8-5=3,now b=3 so, a=5 and b=3

#include<stdio.h> #include<conio.h> void main() { int a,b; printf("\n Enter the 2 numbers"); scanf("%d%d",&a,&b); //swaping of 2 numbers without using temp variable a=a+b; b=a-b; a=a-b; /* or a=a*b; b=a/b; a=a/b; */ printf("\n A = %d \n B = %d\n"); getch(); }

JAVA
import java.io.*; class binary_search { public static void main(String args[])throws IOException { int i; InputStreamReader x=new InputStreamReader(System.in); BufferedReader y=new BufferedReader(x); int a[]=new int[10]; System.out.println("ENTER THE NUMBER TO BE SEARCHED"); int n=Integer.parseInt(y.readLine()); System.out.println("ENTER 10 NUMBERS FOR THE ARRAY"); for(i=0;i<10;i++) { a[i]=Integer.parseInt(y.readLine()); } System.out.println("CONTENTS OF ARRAY ARE"); for(i=0;i<10;i++) { System.out.println(a[i]); } System.out.println("NUMBER TO BE SEARCHED IS "+n); int p=-1,mid,l=0,u=9; while(l<=u) { mid=(l+u)/2; if(a[mid]==n) { p=mid; break; } else if(n> a[mid]) { l=mid+1; } else if(n<a[mid]) { u=mid-1; } } if(p==-1) { System.out.println("NUMBER DOES NOT EXIST IN THE ARRAY"); } else { System.out.println("NUMBER EXISTS AT THE INDEX "+p); } } }

Bubble Sorting in Java

Introduction In this example we are going to sort integer values of an array using bubble sort. Bubble sort is also known as exchange sort. Bubble sort is a simplest sorting algorithm. In bubble sort algorithm array is traversed from 0 to the length-1 index of the array and compared one element to the next element and swap values in between if the next element is less than the previous element. In other words, bubble sorting algorithm compare two values and put the largest value at largest index. The algorithm follow the same steps repeatedly until the values of array is sorted. In worst-case the complexity of bubble sort is O(n2) and in best-case the complexity of bubble sort is (n). Code description: Bubble Sorting is an algorithm in which we are comparing first two values and put the larger one at higher index. Then we take next two values compare these values and place larger value at higher index. This process do iteratively until the largest value is not reached at last index. Then start again from zero index up to n-1 index. The algorithm follows the same steps iteratively unlit elements are not sorted. Working of bubble sort algorithm: Say we have an array unsorted A[0],A[1],A[2]................ A[n-1] and A[n] as input. Then the following steps are followed by bubble sort algorithm to sort the values of an array. 1.Compare A[0] and A[1] . 2.If A[0]>A[1] then Swap A[0] and A[1]. 3.Take next A[1] and A[2]. 4.Comapre these values. 5.If A[1]>A[2] then swap A[1] and A[2] ............................................................... ................................................................ at last compare A[n-1] and A[n]. If A[n-1]>A[n] then swap A[n-1] and A[n]. As we see the highest value is reached at nth position. At next iteration leave nth value. Then apply the same steps repeatedly on A[0],A[1],A[2]................ A[n-1] elements repeatedly until the values of array is sorted.

In our example we are taking the following array values 12 9 4 99 120 1 3 10 The basic steps followed by algorithm:In the first step compare first two values 12 and 9. 12 9 4 99 120 1 3 10 As 12>9 then we have to swap these values Then the new sequence will be 9 12 4 99 120 1 3 10 In next step take next two values 12 and 4 9 12 4 99 120 1 3 10 Compare these two values .As 12>4 then we have to swap these values. Then the new sequence will be 9 4 12 99 120 1 3 10 We have to follow similar steps up to end of array. e.g. 9 4 12 99 120 1 3 10 9 4 12 99 120 1 3 10 9 4 12 99 1 120 3 10 9 4 12 99 1 120 3 10 9 4 12 99 1 3 120 10 9 4 12 99 1 3 10 120 When we reached at last index .Then restart same steps unlit the data is not sorted. The output of this example will be : 1 3 4 9 10 12 99 120 The code of the program : public class bubbleSort{ public static void main(String a[]){ int i;

int array[] = {12,9,4,99,120,1,3,10}; System.out.println("Values Before the sort:\n"); for(i = 0; i < array.length; i++) System.out.print( array[i]+" "); System.out.println(); bubble_srt(array, array.length); System.out.print("Values after the sort:\n"); for(i = 0; i <array.length; i++) System.out.print(array[i]+" "); System.out.println(); System.out.println("PAUSE"); } public static void bubble_srt( int a[], int n ){ int i, j,t=0; for(i = 0; i < n; i++){ for(j = 1; j < (n-i); j++){ if(a[j-1] > a[j]){ t = a[j-1]; a[j-1]=a[j]; a[j]=t; } } } } }

Output of the example: C:\array\sorting>javac bubbleSort.java C:\array\sorting>java bubbleSort Values Before the sort: 12 9 4 99 120 1 3 10 Values after the sort: 1 3 4 9 10 12 99 120 PAUSE C:\array\sorting>_

Binary Search in Java


In this section, we are going to search an element from an array using Binary Search. The advantage of a binary search over a linear search is astounding for large numbers. It can be done either recursively or iteratively. In the given code, we have allowed the user to enter the numbers to be stored into the

array.Then we start the search from the middle element of the array. If the middle element is equal to the searched value, the algorithm stops otherwise we have two cases: 1)If searched value is less than the middle element. In this case, again get the middle element of the first half of the specified array. 2)If searched value is greater, than the middle element. In this case, again get the middle element of the second half of the specified array. This will continue until we get the searched element. Here is the code: import java.util.*; public class BinarySearch { public static void main(String[] args) { int[] intArray = new int[10]; int searchValue = 0, index; System.out.println("Enter 10 numbers"); Scanner input = new Scanner(System.in); for (int i = 0; i < intArray.length; i++) { intArray[i] = input.nextInt(); } System.out.print("Enter a number to search for: "); searchValue = input.nextInt(); index = binarySearch(intArray, searchValue); if (index != -1) { System.out.println("Found at index: " + index); } else { System.out.println("Not Found"); } } static int binarySearch(int[] search, int find) { int start, end, midPt; start = 0; end = search.length - 1;

while (start <= end) { midPt = (start + end) / 2; if (search[midPt] == find) { return midPt; } else if (search[midPt] < find) { start = midPt + 1; } else { end = midPt - 1; } } return -1; } } Output Enter 10 numbers: 1 2 3 4 5 6 7 8 9 10 Enter a number to search for:5 Found at index: 4

Insertion Sort In Java

Introduction In this example we are going to sort integer values of an array using insertion sort. Insertion sorting algorithm is similar to bubble sort. But insertion sort is more efficient than bubble sort because in insertion sort the elements comparisons are less as compare to bubble sort. In insertion sorting algorithm compare the value until all the prior elements are lesser than compared value is not found. This mean that the all previous values are lesser than compared value. This algorithm is more efficient than the bubble sort .Insertion sort is a good choice for small values and for nearly-sorted values. There are more efficient algorithms such as quick sort, heap sort, or merge sort for large values . Positive feature of insertion sorting: 1.It is simple to implement 2.It is efficient on (quite) small data values 3.It is efficient on data sets which are already nearly sorted. The complexity of insertion sorting is O(n) at best case of an already sorted array and O(n2) at worst case . Code description: In insertion sorting take the element form left assign value into a variable. Then compare the value with previous values. Put value so that values must be lesser than the previous values. Then assign next value to a variable and follow the same steps relatively until the comparison not reached to end of array. Working of insertion sorting:

The code of the program : public class InsertionSort{ public static void main(String a[]){ int i; int array[] = {12,9,4,99,120,1,3,10}; System.out.println("\n\n RoseIndia\n\n"); System.out.println(" Selection Sort\n\n"); System.out.println("Values Before the sort:\n"); for(i = 0; i < array.length; i++) System.out.print( array[i]+" "); System.out.println(); insertion_srt(array, array.length); System.out.print("Values after the sort:\n");

for(i = 0; i <array.length; i++) System.out.print(array[i]+" "); System.out.println(); System.out.println("PAUSE"); } public static void insertion_srt(int array[], int n){ for (int i = 1; i < n; i++){ int j = i; int B = array[i]; while ((j > 0) && (array[j-1] > B)){ array[j] = array[j-1]; j--; } array[j] = B; } } }

Output of the example: C:\array\sorting>javac InsertionSort.java C:\array\sorting>java InsertionSort RoseIndia Selection Sort Values Before the sort: 12 9 4 99 120 1 3 10 Values after the sort: 1 3 4 9 10 12 99 120 PAUSE C:\array\sorting>_

Selection Sort In Java

Introduction In this example we are going to sort the values of an array using selection sort. In selection sorting algorithm, find the minimum value in the array then swap it first position. In next step leave the first value and find the minimum value within remaining values. Then swap it with the value of minimum index position. Sort the remaining values by using same steps. Selection sort is probably the

most intuitive sorting algorithm to invent. The complexity of selection sort algorithm is in worst-case, average-case, and best-case run-time of (n2), assuming that comparisons can be done in constant time. Code description: In selection sort algorithm to find the minimum value in the array. First assign minimum index in key (index_of_min=x). Then find the minimum value and assign the index of minimum value in key (index_of_min=y). Then swap the minimum value with the value of minimum index. At next iteration leave the value of minimum index position and sort the remaining values by following same steps. Working of the selection sort : Say we have an array unsorted A[0],A[1],A[2]................ A[n-1] and A[n] as input. Then the following steps are followed by selection sort algorithm to sort the values of an array . (Say we have a key index_of_min that indicate the position of minimum value) 1.Initaily varaible index_of_min=0; 2.Find the minimum value in the unsorted array. 3.Assign the index of the minimum value into index_of_min variable. 4.Swap minimum value to first position. 5.Sort the remaining values of array (excluding the first value). The code of the program : public class selectionSort{ public static void main(String a[]){ int i; int array[] = {12,9,4,99,120,1,3,10}; System.out.println("\n\n RoseIndia\n\n"); System.out.println(" Selection Sort\n\n"); System.out.println("Values Before the sort:\n"); for(i = 0; i < array.length; i++) System.out.print( array[i]+" "); System.out.println(); selection_srt(array, array.length); System.out.print("Values after the sort:\n"); for(i = 0; i <array.length; i++) System.out.print(array[i]+" ");

System.out.println(); System.out.println("PAUSE"); } public static void selection_srt(int array[], int n){ for(int x=0; x<n; x++){ int index_of_min = x; for(int y=x; y<n; y++){ if(array[index_of_min]<array[y]){ index_of_min = y; } } int temp = array[x]; array[x] = array[index_of_min]; array[index_of_min] = temp; } } }

Output of the example: C:\array\sorting>javac selectionSort.java C:\array\sorting>java selectionSort RoseIndia Selection Sort Values Before the sort: 12 9 4 99 120 1 3 10 Values after the sort: 120 99 12 10 9 4 3 1 PAUSE C:\array\sorting>_

Generating Random Number

In many places you need random numbers to fulfill your requirements. Java provides classes to help you in generation random numbers for your application. Random Number is the frequently used to generate numbers either in the range or without specifying a range. This section shows you how to create a random number and example provided here will help you easily understand and use the code to generate random numbers in your java application.

The Random class of java.util package can be used to generate a random number in the range which can be specified. If you don't mention the range value then program will generate any random number for your. Methods and APIs Explanation: Random: Random is the class of java.util.*; package. This class is used to create a random number through it's created object using the 48-bit seed which is modified by the linear congruential formula. nextInt(): This method returns a random number in random number generator's sequence. If you pass a value to the method then the method return the random number in the mentioned range otherwise it will generate the random number in sequence according to the random number generator. Here is the code of the program: import java.util.*; public class GenerateRandomNumber{ public static void main(String[] args){ Random rand = new Random(); int num = rand.nextInt(10); System.out.println("Generated Random Number between 0 to 10 is : " + num); int numNoRange = rand.nextInt(); System.out.println("Generated Random Number without specifying any range is : " + numNoRange); } }

You might also like