Showing posts with label Sorting. Show all posts
Showing posts with label Sorting. Show all posts

Tuesday, November 5, 2024

BlueJ Program On 2 D Array and Sorting


Details of The Program: CLICK HERE

import java.io.*; 
public class P 
{ 
void sort(int arr[])          //Taking single dimension array as parameter 
{

int i, j, size = arr.length, temp,flag;

/*'size' holds the number of values in the array */ 
for(i=0;i 
{

flag=0; 
/*Sorting using bubble sort technique, so if there is no exchange of values in one pass there is no need to run the loop */ 
for(j=0;j 
{ 
if(arr[j]>arr[j+1])

{
flag=1; temp = arr[j]; 
arr[j] = arr[j+1]; 
arr[j+1] = temp; 
}

} 
if(flag==0)

break;
}

}

void show(int arr[][]) /*Taking 2D array as parameter*/ 
{

int i, j; for(i=0;i

{

for(j=0;j 
/* arr[i] gives one row at a time. arr[i].length gives the number of values in each row */ 
{ 
System.out.print(arr[i][j]+"\t"); 
}

System.out.println();

} 
}
 void sort2D(int arr[][]) 
{ 

/* In java, array is an object, so here the function calling technique is call be reference means any changes made to the formal parameter in this function will be reflected in the original parameter.*/


int i, j; 
for(i=0;i 
{ 
sort(arr[i]); 
} 
}
public static void main(String args[])throws Exception 
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

P obj = new P(); int arr[][], m, n, i, j; 
System.out.println("Enter the number of rows: "); 
m = 
Integer.parseInt(br.readLine()); 
System.out.println("Enter the number of columns: ");
n = Integer.parseInt(br.readLine()); 
if(m< 2 && m >9||n >9 && n< 2) 
{

System.out.println("Matrix out of range"); System.exit(0);

} 
arr = new int[m][n]; 
for(i=0;i< 
{
System.out.println("Enter values for row no "+(i+1) + ":"); for(j=0;j
{

System.out.print("\nColumn No " + (j+1) + ":"); arr[i][j] = Integer.parseInt(br.readLine()); 
} 
}
System.out.println("Original Matrix: ");
obj.show(arr); 
obj.sort2D(arr);

System.out.println("Matrix after sorting rows: "); obj.show(arr);
}
}

Variable Description

Type
Name
Use
BufferedReader
br
Intakes limit from user
int
arr
2 D array to hold the values
Int
m
Holds no of rows in the array
int
n
Holds no of columns in the


array

int
I,j
Loop Control Variable
int
size
Holds the no of elements in


each row the array
Algorithm




Step 1: Create BufferedReader object ‘br’ and int type variables ‘n’ and 'm' to store the column and row size of the 2 D array.

Step 2: Values of ‘n’ and 'm' are checked for validity and if it is invalid, terminate the program otherwise create the 2 D array 'arr'.

Step 3: Stores the values in the two dimensional array 'arr'.

Step 4: Display the original array


Step 5: Pass the two dimensional array to function 'sort2D()' which sends each rows of the 2 d array to 'sort()' function which sorts the elements bubble sort technique.


Back To 2018 Computer Practical Paper: CLICK HERE

Sunday, June 6, 2021

C Array And Sorting

 Details of the program:  Write a C program that Takes a 1-dimensional array a as input (of size 20)
Now, sort the first 5 elements in descending order and sort the last 15 elements in ascending order (do not use any pre-defined function for sorting) in a using at most 2 loops. Replace the smallest element with -1 without using any more loop and display the final array elements

#include<stdio.h>
void main()
{

int arr[20];
int i,j,t,min,index;
for(i=0;i<20;i++)
{
printf("\nValues:");
scanf("%d",&arr[i]);
 
}
for(i=0;i<5-1;i++)
{
for(j=i+1;j<5;j++)
{
if(arr[i]<arr[j])
{
t=arr[i];
arr[i]=arr[j];
arr[j]=t;
}
}
}
for(i=5;i<20-1;i++)
{
for(j=i+1;j<20;j++)
{
if(arr[i]>arr[j])
{
t=arr[i];
arr[i]=arr[j];
arr[j]=t;
}
}
}
if(arr[4]<arr[5])
arr[4]=-1;
else
arr[5]=-1;
printf("\nElements as follows\n");
for(i=0;i<20;i++)
printf(" %d",arr[i]);
getch();
}

Tuesday, September 8, 2020

Sorting An Array - First 10 Values Using Selection Sort and The Next 10 Values Bobble Sort

 This is an array program where 20 values are stored in an array and the elements are sorted. There is a twist in the sorting process, 1st 10 values will be sorted using selection sort technique and the last 10 values will be sorted using bubble sort.


import java.util.*;

class A

{

  int arr[]=new int[20];

  int i,j,t,flag;

  Scanner sc=new Scanner(System.in);

  void show()

  {

      for(i=0;i<20;i++)

      {

           System.out.print("\nValue:");

           arr[i]=sc.nextInt();

        }

        System.out.println("\nElements as follows:");

        for(i=0;i<20;i++)

      {

           System.out.print(" "+arr[i]);          

        }        

        for(i=0;i<9;i++)

        {

          for(j=i+1;j<10;j++)

          {

              if(arr[i]>arr[j])

                {

                t=arr[i];

                arr[i]=arr[j];

                arr[j]=t;

                }

            }

        }         

         for(i=10;i<20;i++)

        {             

             flag=0;

          for(j=10;j<30-i-1;j++)

          {               

              if(arr[j]>arr[j+1])

                {                   

                    flag=1;

                t=arr[j];

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

                arr[j+1]=t;

                }

            }            

            if(flag==0)

            break;           

        }        

        System.out.println("\nAfter sorting, values as follows:");

        for(i=0;i<20;i++)

      {

        System.out.print(" "+arr[i]);          

      }  

        }

        public static void main(String args[])

        {

             A obj=new A();

             obj.show();

            }

        }


Sample Input Output



Value:33

Value:22

Value:11

Value:22

Value:33

Value:44

Value:77

Value:6

Value:5

Value:4

Value:55

Value:6

Value:55

Value:8

Value:77

Value:5

Value:467

Value:54

Value:66

Value:78

Elements as follows:

 33 22 11 22 33 44 77 6 5 4 55 6 55 8 77 5 467 54 66 78

After sorting, values as follows:

 4 5 6 11 22 22 33 33 44 77 5 6 8 54 55 55 66 77 78 467

Monday, May 6, 2013

Arranging values in an array in zig zag manner



Few values are to be taken from user and the values will be arranged in ascending order but in a zig zag manner. The smallest value will be placed at the extreme left side (at zero index location) and the next value will be at the extreme right location (last index location). Similarly the third value in the ‘1’ index location and 4rth value at the (size-2) location of the array and so on.

Here is the BlueJ program


import java.io.*;
class Ab1
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
 int c=0,minvalue,minindex,k,arr[],i,j,n,t,x=0,y;
 public void take() throws Exception
 {
 System.out.println("How many elements:");
 n=Integer.parseInt(br.readLine());
 arr=new int[n];
 for (i=0;i< n;i++)
 {
 System.out.println("How many elements:");
 arr[i]=Integer.parseInt(br.readLine());
 }
 System.out.println("\nOriginal elements in the array=");
      for(i=0;i< n;i++)
    System.out.print("  "+arr[i]);
  y=n-1;
 for(i=x;i<=y;i++)
 {
  minvalue=arr[i];
  minindex=i;
    for(j=i+1;j<=y;j++)
  {
   if(arr[j]
   {
    minvalue=arr[j];
    minindex=j;
    }
    }
    if(c%2==0)
    {
     t=arr[x];
     arr[x]=minvalue;
     arr[minindex]=t;
     x++;
     }
     else
    {
    t=arr[y];
     arr[y]=minvalue;
     arr[minindex]=t;
     y--;
     i--;
     }
     c++;
     }
     System.out.println("\nFinal elements in the array=");
    for(i=0;i< n;i++)
    System.out.print("   "+arr[i]);
   }
   public static void main(String args[])throws Exception
   {
   Ab1 ob=new Ab1();
   ob.take();
   }
   }


Tuesday, August 28, 2012

C Language program on Shell Sort


This sort technique works by comparing the list elements that are separated by a specific distance i,e a gap until the elements compared within the current gap are in order. Then the gap is reduced and the process continues. When the gap reaches 0 and no interchange is possible then the list is completely sorted.

Suppose a list contains the following elements : 3,44,2,1,5,34,12,22
Size of the above list is 8
gap=Size/2=4

The sorting can be demonstrate to take place as follows
3       44    2    1    5      3     12     22
      3      44    2    1    5      4     12     22
      3      4      2    1    5      44   12     22
      3      4      2    1    5      44   12     22
      3      4      2    1    5      44   12     22
     3       4      2    1    5      44   12     22
     2      4       3    1    5      44    12    22
     2      1       3    4    5      44    12    22
     2      1       3    4    5      44    12    22
     2      1       3    4    5      44    12    22
     2      1       3    4    5      44    12    22
     2      1       3    4    5      22    12    44
     2      1       3    4    5      22    12    44
     1      2       3    4    5      22    12    44
     1      2       3    4    5      22    12     44
     1     2        3    4    5      22    12     44
     1     2        3    4    5      22    12     44
     1     2       3     4    5      22    12     44
     1     2       3     4    5      12    22     44
     1     2       3     4    5      12    22     44



#include< stdio.h>
#include< stdlib.h>
void shell(int arr[],int n)
{
 int t,gap,flag,i;
 gap=n/2;
 do
 {
  do
  {
            flag=0;
            for(i=0;i
            {
             if(arr[i]>arr[i+gap])
             {
              t=arr[i];
              arr[i]=arr[i+gap];
              arr[i+gap]=t;
              flag=1;
             }
            }
            }while(flag);
            gap=gap/2;
  }while(gap);
 }
 void main()
 {
  int val[20],i;
  printf("\nUnsorted list is as follows\n");
  randomize();
  for(i=0;i< 20;i++)
  {
            val[i]=rand()%100;
            printf("%4d",val[i]);
  }
  shell(val,20);
             printf("\nSorted list is as follows\n");
  for(i=0;i< 20;i++)
  {
            printf("%4d",val[i]);
  }
}

Friday, June 22, 2012

MERGE SORT ALGORITHM AND PROGRAM USING C LANGUAGE


Suppose there are two arrays int a [10] and int b [10].The operation that combines this two arrays is called merging. If the arrays are not in sorted order then we may first sort them and after that may be merged. It is also possible to merge them first and after that the sorting will be done.

Algorithm for sorting the two arrays first and then merging them:-

A and B are two arrays with n and m number of elements. Both the arrays are in sorted order. C is the final array where the final values will be stored. I, J and K are three integer type variables with initial value 0 .They will be used as array index or the three arrays.
Repeat the following steps while ((I< n) and (J< m))
If A [I] < B [J]
C [K] =A [I]
I=I+1
K=K+1
Else if A [I] >B [J]
C [K] =B [J]
J=J+1
K=K+1
Else [This situation means both are same, so any one of the values can be set in the final array]
C [K] =A [I]
I=I+1
J=J+1
K=K+1
[End of loop]
If I< n [means first array has more values]
Repeat the following steps for I=I, I+1…n-1
C [K] =A [I]
I=I+1
K=K+1
[End of loop]
Else If (J, m)
Repeat the following steps for J=J, J+1…m-1
C [K] =B [J]
J=J+1
K=K+1
[End of loop]
End

Program on merge sort:-

# include< stdio.h>
bsort(int n, int l[])
{
int flag = 1 ;
int i, j, k, temp;
for(j = 0 ; j< n - 1; j++)
{
for(k = 0 ; k<  n - j - 1 ; k++)
{
if(l[k] > l[k+1])
{
temp = l[k];
l[k] = l[k+1];
l[k+1] = temp ;
flag = 0;
}
}
if(flag)
break ;
else
flag = 1;
}
printf("\n Entered  list as  follows in");
printf("\n Ascending order: ");
for(i = 0 ; i < n ; i++)
printf(" %d", l[i]);
}
 msort( int n, int list_a[], int m ,int list_b[], int result_list[] )
{
int i = 0;
int j = 0;
int k = 0;
int ch, l;
while((i < n) &&(j< m))
{
if(list_a[i] < list_b[j])
{
result_list[k] = list_a[i];
i++;
k++;
}
else if(list_a[i] > list_b[j])
{
result_list[k] = list_b[j];
j++;
k++;
}
else
{
result_list[k] = list_a[i];
i++;
j++;
k++;
}
printf("\n");
for(ch = 0; ch < k; ch++)
printf(" %d", result_list[ch]);
}
if(i < n )
{
for(l = i ; l < n ; l++)
{
result_list[k] = list_a[i];
i++;
k++;
printf("\n");
for(ch = 0; ch < k; ch++)
printf(" %d", result_list[ch]);
}
}
else if(j < m)
{
for(l = j; l< m; l++)
{
result_list[k] = list_b[j];
j++;
k++;
printf("\n");
for(ch = 0; ch < k; ch++)
printf(" %d", result_list[ch]);
}
}
return k;
}
void main()
{
int list_a[100],list_b[100];
int result[200];
int n, m, k, i;
clrscr();
printf("\n Input the number of elements of list_a: ");
scanf("%d", &n);
for(i = 0; i< n ; i++)
{
printf("\n Input the element: %d: ",  i+1);
scanf("%d", &list_a[i]);
}
bsort(n, list_a);
 printf("\n Input the number of elements of list_b:");
scanf("%d", &m);
for(i = 0 ; i< m ; i++)
{
printf("\n Input the element: %d: ", i+1);
scanf("%d", &list_b[i]);
}
 bsort(m, list_b);
 k = msort( n, list_a, m , list_b, result);
printf("\n Sorted list is as follows:\n");
for(i = 0 ; i< k ; i++)
{
printf(" %d", result[i]);
}
getch();
}



Insertion Sort in C Language – Program, Algorithm and Time Complexity


In insertion sorting technique, the elements are scanned from left to right and insert each element in its proper location in the previously sorted list. So in an array Arr  of n number of elements Arr[1] is assumed to be sorted. Then in the second iteration Arr[2] is inserted either before Arr[1] or after Arr[1] so that Arr[1] and Arr[2] are sorted. Similarly Arr[3] will be inserted either before Arr[1] , after Arr[3] or between Arr[1] and Arr[2] and so on. Now the problem is , where to insert Arr[x] in an sorted sub-array. This can be achieved by comparing Arr[x] with Arr[x-1] , Arr[x-2],Arr[x-3] and so on until it meets a value that less than or equal to Arr[x].Suppose Arr[j] is such value. Then Arr[x] will be positioned at Arr[j+1] location and all elements with which Arr[x] was compared will move forward by one location. From the above it is clear that there must be always an element Arr[j] such that Arr[j]<=Arr[x].So always put some small number say 0 in Arr[0] so that the above condition will be useful.

C Program on insertion sort

# include  < stdio.h>
#define number 10
/* actually 11 values will be inserted in this array, value in the 0 index being a small value (0)*/
void iS(int arr[], int n)
{
int p,temp,i,k,x;
arr[0] = 0;
for(i = 1 ; i <= n; i++)
{
x=0;
p= i -1;
temp = arr[i];
/* In the iteration of the loop 'p' is 0 and 'i' is 1.So 'temp' will be the second element of the array , means the first valid value of the array while 'arr[p]' will be the smallest value (-0).So in the first iteration there will be no interchange of values. */
while(temp < arr[p])
{
  arr[p+1] = arr[p];
  p --;
  x++;
/* In the second iteration,'arr[i]' means the second valid value while 'arr[p]' is the value of the previous location.The loop will continue to search the location for 'temp' if 'temp' is less than its previous value and during this process the greater values will be shifted one location right until the specific value 'temp' becomes equal to or greater than its previous value. At the end set 'temp' in its proper location with the statement 'arr[p+1]=temp' */
}
arr[p+1] = temp;
printf("Step(%d):-", i);
for(k = 1; k <= n; k++)
printf(" %d", arr[k]);
if(x!=0)
printf("-- took %d comparisions to place %d.",x,temp);
else
printf("--No interchange of position for %d.",temp);
printf("\n");
}
}
void display(int arr[], int n)
{
int i;
printf("\n Sorted list is as follows\n");
for(i = 1; i <= n; i++)
printf(" %d", arr[i]);
}
void main()
{
int list[20];
int i;
clrscr();
printf("\n Number of elements in the list: %i", number);
printf("\n Enter ten values:-\n");
for(i = 1; i <= number; i++)
{
scanf("%d",&list[i]);
}
printf("\n Step wise result is as follows \n\n");
iS(list,number);
display(list, number);
getch();
}

Insertion sort program without any extra location

#include < stdio.h>
void ins(int arr[],int n)
{
 int i,j,k,t,flag;
 for(i=1;i< n;i++)
 {
  k=0;
  flag=0;
  while(1)
  {
   if(i< k)
   break;
   /* means there is no smaller value at left side of the value positioned at location 'i'*/
 if(arr[i]< arr[k])
 {
  t=arr[k];
  arr[k]=arr[i];
  /* take the value to be shifted right side in 't' and insert the value of location 'i' at the location 'k' */
  flag=1;
 }
  if(flag==1)
  {
   for(j=i;j>k+1;j--)
   {
    arr[j]=arr[j-1];
    /* this shifts the values in the right ward direction */
    }
   arr[j]=t;
   /* positioning the value lifted from the left side to just right of it */
   }
   else
   k++;
   /* trying with next value */
   if(flag==1)
   break;
   /* in case of shifting, try with another value */
   }
   }
   }
   void main()
   {
    int i,arr[10];
    clrscr();
    for(i=0;i<10;i++)
    {
     printf("\nValue=");
     scanf("%d",&arr[i]);
    }
    printf("\nBEFORE SORTING\n");
    for(i=0;i<10;i++)
    printf("%4d",arr[i]);
    ins(arr,10);
    printf("\nAFTER SORTING\n");
    for(i=0;i<10;i++)
    printf("%4d",arr[i]);
    getch();
   }
                      
Algorithm of Insertion Sort :- ARR is an array which holds N+1 number of values.ARR[0] is made to store a very small value , so actual values stored in the array is N.TEMP is a variable which will help to interchange values while required. I is loop control variable. P is another variable.
Repeat the following steps for I=1,2,3…N
Set TEMP=ARR[I]
Set P=I-1
While TEMP < ARR[P]
Set ARR[P+1]=ARR[P]
Set P=P-1
[End of inner loop]
Set ARR[P]=TEMP
[End of outer loop]
End

Complexity of insertion sort:
In worst case while the list is arranged in reversed order, the inner loop will make k-1 comparisons to set the value of kth position in its actual location. So the time complexity f(x)=1+2+3+….+(n-1)
=n(n-1)/2
=O(n2)
In average case, there will be approximately (k-1)/2 comparisons for each element to set the value in its position. So f(x)=1/2+2/2+3/2+……(n-1)/2
 = n(n-1)/4
 =O(n2)

Subscribe via email

Enter your email address:

Delivered by FeedBurner