Sie sind auf Seite 1von 52

A

Project Stage-1 Report


On
Sorting Algorithms
Submitted
In partial fulfilment
For the award of the Degree of
Bachelor of Technology
In
Computer Science &Engineering & Information Technology

Submitted To: Submitted By:

Mr. Sayar Singh Shekhawat Vishal(16EAICS182)


Head of Department Vishal Yadav (16EAICS185)
Sachin Kumar Jha(16EAICS143)
Ankit Kumar(16EAICS034)

Department of Computer Science &Engineering & Information Technology


Arya Institute of Engineering & Technology, Jaipur

Rajasthan Technical University, Kota

[ December 2019 ]

1
Candidate’s Declaration

I hereby declare that the work, which is being presented in the minor project,
entitled “Sorting Algorithms “in partial fulfilment for the award of Degree of
“Bachelor of Technology” in Department of Computer Science & Engineering
with Specialization in Computer Engineering and submitted to the Department
of Computer Science & Engineering, Arya Institute of Engineering &
Technology, is a record of my own investigations carried under the Guidance of
Mr. Indrajeet sinha, Associate Professor, Department of Computer Science &
Engineering.

(Signature of Candidate)

Sachin Jha (16EAICS143)


Vishal (16EAICS182)
Vishal Yadav (16EAICS185)
Ankit Kumar (16EAICS 034)

2
Acknowledgment

We wish to express our deep sense of gratitude to our project guide Er. Manish Choubisa
Assistant Professor, Arya Institute of engineering and technology, Jaipur, for guiding us from
the inception till the completion of the project. We sincerely acknowledgment him for giving
his valuable guidance, support for literature survey, critical reviews and comments for our
project.

We would like to first of all express our thanks to Dr. Arvind agarwal, Chairman, Arya group
of colleges and Dr. Puja Agarwal, managing director, Arya group of colleges, for providing us
such a great infrastructure and environment for our overall development.

We express sincere thanks to Mr. Yogesh Bhomia, Principal, AIET for his kind cooperation and
extendible support toward the completion of our project Words are inadequate in offering our
thanks to Mr. SS Shekhawat, Head, Department of CSE, for consistent encouragement and
support for shaping our project in the presentable form.

We also like to express our thanks to all supporting CSE faculty members who have been a
constant source of encouragement for successful completion of the project.

Sachin Kumar Jha(16EAICS143)


Vishal(16EAICS183)
Vishal Yadav (16EAICS185)
Ankit Kumar(16EAICS034)

3
ABSTRACT

It is a desktop application using core java that represent several sorting algorithms, such as
Merge sort, Quick sort, Insertion sort, Bubble sort, Selection sort and heap sort. The real-life
use for this project is to sort a set of given number by a number of sorting algorithms because
every sorting algorithm has it’s pro and cons.
Sorting algorithm is an algorithm that puts elements of a list in a certain order. The most
frequently used orders are numerical order and lexicographical order. Efficient sorting is
important for optimizing the efficiency of other algorithms (such as search and merge
algorithms) that require input data to be in sorted lists. Sorting is also often useful for canonical
zing data and for producing human-readable output.

4
ARYA INSTITUTE OF ENGINEERING & TECHNOLOGY
SP-40, RIICO Industrial Area, Jaipur (Raj)-302022

Department of Computer Science & Engineering

Certificate

This is to certify that the work, which is being presented in the Project stage-1
report for “SFC The Game master” submitted by Mr. Sachin Jha, Vishal, Vishal
Yadav, Ankit Kumar, students of fourth year (VII Sem) B.Tech. in Computer
Engineering as a partial fulfilment for the award of degree of bachelor of
technology is a record of student’s work carried out and found satisfactory for
submission.

Mr. Indrajeet Sinha Mr. Sayar Singh Shekhawat

Project Coordinator Head of Department

5
Table of content

1. Cover Page ……………………………………………………….

2. Candidate’s Declaration ……………………………………….

3. Certificate…………………………………………………………

4. Acknowledgement…………………………………………………

5. Abstract…………………………………………………………….

6. Table of content…………………………………………………….

7. List of Figure……………………………………………………….

8. Chapter 1 Introduction 8

9. Chapter 2 Requirements 10

a) 2.1 hardware

b) 2.2 Software

10. Chapter 3 Coding 12

11. Chapter 4 Project Flow 23

Conclusion 39

References 40

6
LIST OF FIGURES

Fig 1. Command Execution

Fig 2. Interactive Screen

Fig 3. Menu

Fig 4. New User Registration

Fig 5. Symptoms

Fig 6. Types of cancer

6(a). Blood cancer

6(b). Breast cancer

6(c). Lung cancer

Fig 7. Game Concept

Fig 8. Training

8(a). Cancer basis


8(b). Types of cancer
8(c). Components

7
Chapter 1

Introduction

Sorting is any process of arranging items systematically, In computer science, arranging in an


ordered sequence is called "sorting". Sorting is a common operation in many applications, and
efficient algorithms to perform it have been developed.

Sorting algorithm
A sorting algorithm is an algorithm that puts elements of a list in a certain order. The most
frequently used orders are numerical order and lexicographical order. Efficient sorting is
important for optimizing the efficiency of other algorithms (such
as search and merge algorithms) that require input data to be in sorted lists. Sorting is also
often useful for canonicalizing data and for producing human-readable output. More formally,
the output of any sorting algorithm must satisfy two conditions.

Popular sorting algorithms


While there are a large number of sorting algorithms, in practical implementations a few
algorithms predominate. Insertion sort is widely used for small data sets, while for large data
sets an asymptotically efficient sort is used, primarily heap sort, merge sort, or quicksort.
Efficient implementations generally use a hybrid algorithm, combining an asymptotically
efficient algorithm for the overall sort with insertion sort for small lists at the bottom of a
recursion. Highly tuned implementations use more sophisticated variants, such as Tim
sort (merge sort, insertion sort, and additional logic), used in Android, Java, and Python,
and intro sort (quicksort and heap sort),
Bubble/Shell sort: Exchange two adjacent elements if they are out of order. Repeat until array
is sorted
Insertion sort: Scan successive elements for an out-of-order item, then insert the item in the
proper place.
Selection sort: Find the smallest (or biggest) element in the array, and put it in the proper
place. Swap it with the value in the first position. Repeat until array is sorted.
Quick sort: Partition the array into two segments. In the first segment, all elements are less
than or equal to the pivot value. In the second segment, all elements are greater than or equal
to the pivot value. Finally, sort the two segments recursively.

8
Merge sort: Divide the list of elements in two parts, sort the two parts individually and then
merge it.

TYPES OF SORTING

The techniques of sorting can be divided into two categories. These are:

 Internal Sorting

 External Sorting

Internal Sorting: If all the data that is to be sorted can be adjusted at a time in the main memory,
the internal sorting method is being performed.

External Sorting: When the data that is to be sorted cannot be accommodated in the memory at
the same time and some has to be kept in auxiliary memory such as hard disk, floppy disk,
magnetic tapes etc, then external sorting methods are performed.

THE COMPLEXITY OF SORTING ALGORITHM

The complexity of sorting algorithm calculates the running time of a function in which 'n'
number of items are to be sorted. The choice for which sorting method is suitable for a problem
depends on several dependency configurations for different problems. The most noteworthy of
these considerations are:

 The length of time spent by the programmer in programming a specific sorting program

 Amount of machine time necessary for running the program

 The amount of memory necessary for running the program.

THE EFFICIENT SORTING TECHNIQUES

To get the amount of time required to sort an array of 'n' elements by a particular method, the
normal approach is to analyse the method to find the number of comparisons (or exchanges)
required by it. Most of the sorting techniques are data sensitive, and so the metrics for them
depends on the order in which they appear in an input array.

9
Various sorting techniques are analysed in various cases and named these cases as follows:

 Best case

 Worst case

 Average case

Hence, the result of these cases is often a formula giving the average time required for a
particular sort of size 'n.' Most of the sort methods have time requirements that range from
O(nlog n) to O(n2).

Worst case analysis:


In the worst-case analysis, we calculate upper bound on running time of an algorithm. We must
know the case that causes maximum number of operations to be executed. For Linear Search,
the worst case happens when the element to be searched (x in the above code) is not present in
the array. When x is not present, the search() functions compares it with all the elements of arr[]
one by one. Therefore, the worst-case time complexity of linear search would be Θ(n).

Average Case Analysis:


In average case analysis, we take all possible inputs and calculate computing time for all of the
inputs. Sum all the calculated values and divide the sum by total number of inputs. We must
know (or predict) distribution of cases. For the linear search problem, let us assume that all
cases are uniformly distributed (including the case of x not being present in array). So we sum
all the cases and divide the sum by (n+1). Following is the value of average case time
complexity.

10
Best Case Analysis (Bogus)
In the best case analysis, we calculate lower bound on running time of an algorithm. We must
know the case that causes minimum number of operations to be executed. In the linear search
problem, the best case occurs when x is present at the first location. The number of operations
in the best case is constant (not dependent on n). So time complexity in the best case would be
Θ(1).

Description about sorting:

1.BUBBLE SORT
Bubble sort is a simple sorting algorithm. This sorting algorithm is comparison-based algorithm
in which each pair of adjacent elements is compared and the elements are swapped if they are
not in order. This algorithm is not suitable for large data sets as its average and worst-case
complexity are of Ο(n2) where n is the number of items.

Bubble Sort compares each pair of array element unless the whole array is completely sorted
in an ascending order. This may cause a few complexity issues like what if the array needs no
more swapping as all the elements are already ascending.

To ease-out the issue, we use one flag variable swapped which will help us see if any swap
has happened or not. If no swap has occurred, i.e. the array requires no more processing to be
sorted, it will come out of the loop.

Pseudocode of Bubble sort algorithm can be written as follows −

Procedure bubbleSort( list : array of items )


loop = list.count;

for i = 0 to loop-1 do:

swapped = false

for j = 0 to loop-1 do:

/* compare the adjacent elements */

11
if list[j] > list[j+1] then

/* swap them */

swap( list[j], list[j+1] )

swapped = true

end if

end for

/*if no number was swapped that means

array is sorted now, break the loop.*/

if(not swapped) then

break

end if

end for

end procedure return list

2.INSERTION SORT
This is an in-place comparison-based sorting algorithm. Here, a sub-list is maintained which is
always sorted. For example, the lower part of an array is maintained to be sorted. An element
which is to be 'inserted in this sorted sub-list, has to find its appropriate place and then it has to
be inserted there. Hence the name, insertion sort.

The array is searched sequentially and unsorted items are moved and inserted into the sorted
sub-list (in the same array). This algorithm is not suitable for large data sets as its average and
worst-case complexity are of Ο(n2), where n is the number of items.

Algorithm

Now we have a bigger picture of how this sorting technique works, so we can derive simple
steps by which we can achieve insertion sort.

Step 1- If it is the first element, it is already sorted. return 1;


Step 2 − Pick next element
12
Step 3 − Compare with all elements in the sorted sub-list
Step 4 − Shift all the elements in the sorted sub-list that is greater than the
value to be sorted
Step 5 − Insert the value
Step 6 − Repeat until list is sorted

Pseudocode:
procedure insertionSort( A : array of items )

int holePosition

int valueToInsert

for i = 1 to length(A) inclusive do:

/* select value to be inserted */

valueToInsert = A[i]

holePosition = i

/*locate hole position for the element to be inserted */

while holePosition > 0 and A[holePosition-1] > valueToInsert do:

A[holePosition] = A[holePosition-1]

holePosition = holePosition -1

end while

/* insert the number at hole position */

A[holePosition] = valueToInsert

end for

end procedure

13
3.Heap sort algorithm

Heap Sort is a popular and efficient sorting algorithm in computer programming. Learning how
to write the heap sort algorithm requires knowledge of two types of data structures - arrays and
trees.

The initial set of numbers that we want to sort is stored in an array e.g. [10, 3, 76, 34, 23, 32] and
after sorting, we get a sorted array [3,10,23,32,34,76]

Heap sort works by visualizing the elements of the array as a special kind of complete binary
tree called heap.

Consider an array Arr which is to be sorted using Heap Sort.

 Initially build a max heap of elements in Arr.


 The root element, that is Arr[1], will contain maximum element of Arr. After that, swap
this element with the last element of Arr and heapify the max heap excluding the last
element which is already in its correct position and then decrease the length of heap by
one.
 Repeat the step 2, until all the elements are in their correct position.

Implementation:

void heap_sort(int Arr[ ])

int heap_size = N;

14
build_maxheap(Arr);

for(int i = N; i >= 2 ; i-- )

swap|(Arr[ 1 ], Arr[ i ]);

heap_size = heap_size - 1;

max_heapify(Arr, 1, heap_size);

Complexity:
maxheap has complexity O(logN), build maxheap has complexity O(N) and we run
maxheap N−1 times in heap_sort function, therefore complexity of heapsort function
is O(NlogN).

4.SELECTION SORT
Selection sort is a simple sorting algorithm. This sorting algorithm is an in-place comparison-
based algorithm in which the list is divided into two parts, the sorted part at the left end and
the unsorted part at the right end. Initially, the sorted part is empty and the unsorted part is the
entire list.

The smallest element is selected from the unsorted array and swapped with the leftmost
element, and that element becomes a part of the sorted array. This process continues moving
unsorted array boundary by one element to the right.

This algorithm is not suitable for large data sets as its average and worst case complexities are
of Ο(n2), where n is the number of items.

15
Algorithm

1. Step 1 − Set MIN to location 0


2. Step 2 − Search the minimum element in the list
3. Step 3 − Swap with value at location MIN
4. Step 4 − Increment MIN to point to next element
5. Step 5 − Repeat until list is sorted

Pseudocode
procedure selection sort

list : array of items

n : size of list

for i = 1 to n - 1

/* set current element as minimum*/

min = i

/* check the element to be minimum */

for j = i+1 to n

if list[j] < list[min] then

min = j;

end if

end for

/* swap the minimum element with the current element*/

if indexMin != i then

swap list[min] and list[i]

16
end if

end for

end procedure

5.Quick sort algorithm

Quick Sort is one of the most efficient sorting algorithms and is based on the splitting of an
array into smaller ones. The name comes from the fact that, quick sort is capable of sorting a
list of data elements significantly faster than any of the common sorting algorithms. And like
Merge sort, Quick sort also falls into the category of divide and conquer approach of problem-
solving methodology.

Quick sort works in the following manner:


1. Taking the analogical view in perspective, consider a situation where one had to sort the
papers bearing the names of the students, by name. One might use the approach as follows:
a. Select a splitting value, say L. The splitting value is also known as Pivot.
b. Divide the stack of papers into two. A-L and M-Z. It is not necessary that the piles
should be equal.
c. Repeat the above two steps with the A-L pile, splitting it into its significant two
halves. And M-Z pile, split into its halves. The process is repeated until the piles
are small enough to be sorted easily.
d. Ultimately, the smaller piles can be placed one on top of the other to produce a
fully sorted and ordered set of papers.
2. The approach used here is recursion at each split to get to the single-element array.
3. At every split, the pile was divided and then the same approach was used for the smaller
piles.
4. Due to these features, quick sort is also called as partition exchange sort.

17
Pseudo algorithm for quick sort

/* low --> Starting index, high --> Ending index */

quickSort(arr[], low, high)

if (low < high)

/* pi is partitioning index, arr[pi] is now

at right place */

pi = partition(arr, low, high);

quickSort(arr, low, pi - 1); // Before pi

quickSort(arr, pi + 1, high); // After pi

18
Chapter 2

REQUIREMENTS
2.1 Hardware requirements

There is no need for any special hardware requirements for this desktop application or SFC
(save from cancer) The-game-Master. A personal computer is capable enough to run this
desktop.

For development of this application, we use java technology at all places.

2.2 Software requirements

Java is a general-purpose programming language that is class based, object-oriented and


designed to have as few implementation dependencies as possible. It is intended to
let application developers “write once run anywhere (WORA)”, meaning that compiled Java
code can run on all platforms that support Java without the need for recompilation. Java
applications are typically compiled to bytecode that can run on any java virtual machine (JVM)
regardless of the underlying computer architecture. The syntax of java is similar to C and C++,
but it has fewer low-level facilities than either of them. As of 2019, Java was one of the
most popular programming languages used in according to Git hub particularly for Client-
Server web applications with a reported 9 million developers.

Java was originally developed by James Gosling at Sun Microsystems (Which has since been
acquired by oracle) and released in 1995 as a core component of Sun Microsystems' java
platform. The original and reference implementations Java compilers, virtual machines,
and class libraries were originally released by Sun under propriety licenses. As of May 2007, in
compliance with the specifications of the Java community process, Sun had relicensed most of
its Java technologies under the GNU general public license. Meanwhile, others have developed
alternative implementations of these Sun technologies, such as the GNU compiler for
JAVA (bytecode compiler), GNU Classpath (standard libraries), and IcedTea Web (browser
plugin for applets).

19
Java is a widely used programming language expressly designed for use in the distributed
environment of the internet. It is the most popular programming language for Android
smartphone applications and is also among the most favoured for the development of edge
devices and the internet of things.

Java is a programming language that produces software for multiple platforms. When a
programmer writes a Java application, the compiled code (known as bytecode) runs on most
operating systems (OS), including Windows, Linux and Mac OS. Java derives much of its
syntax from the C and C++ programming languages.

Java is used for:

1. Mobile applications (Specially Android apps)


2. Desktop applications
3. Web applications
4. Web servers and application servers
5. Games
6. Database connection
7. And much, much more!

Why use Java ?

 Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)
 It is one of the most popular programming languages in the world
 It is easy to learn and simple to use
 It is open-source and free
 It is secure, fast and powerful
 It has a huge community support (tens of millions of developers)
 Java is an object-oriented language which gives a clear structure to programs and allows
code to be reused, lowering development costs
 As Java is close to C++ and C#, it makes it easy for programmers to switch to Java or
vice versa

20
Java Swing

Java Swing is a part of Java Foundation Classes (JFC) that is used to create window-based
applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely
written in java.

Swing is a GUI widget toolkit for Java.[1] It is part of Oracle's Java Foundation Classes (JFC)
– an API for providing a graphical user interface (GUI) for Java programs.

Swing was developed to provide a more sophisticated set of GUI components than the earlier
Abstract Window Toolkit (AWT). Swing provides a look and feel that emulates the look and
feel of several platforms, and also supports a pluggable look and feel that allows applications to
have a look and feel unrelated to the underlying platform. It has more powerful and flexible
components than AWT. In addition to familiar components such as buttons, check boxes and
labels, Swing provides several advanced components such as tabbed panel, scroll panes, trees,
tables, and lists.[2]

Unlike AWT components, Swing components are not implemented by platform-specific code.
Instead, they are written entirely in Java and therefore are platform-independent. The term
"lightweight" is used to describe such an element.[3]

In December 2008, Sun Microsystems (Oracle's predecessor) released the CSS / FXML based
framework that it intended to be the successor to Swing, called JavaFX.[4]

Unlike AWT, Java Swing provides platform-independent and lightweight components.

The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.

21
Most GUI class libraries in C++ are platform specific

 Different hardware capabilities

 Subtle differences between the "look-and-feel" of various Windowing operating


systems

 Abstract Window Toolkit (AWT) is cross-platform

 Swing can observe various OS look-and-feel conventions

Hierarchy of Java Swing classes

The hierarchy of java swing API is given below.

22
Java Abstract Window Toolkit (AWT)

AWT contains large number of classes and methods that allows you to create and manage
graphical user interface (GUI) applications, such as windows, buttons, scroll bars,etc. The AWT
was designed to provide a common set of tools for GUI design that could work on a variety of
platforms. The tools provided by the AWT are implemented using each platform's native GUI
toolkit, hence preserving the look and feel of each platform. This is an advantage of using
AWT.But the disadvantage of such an approach is that GUI designed on one platform may look
different when displayed on another platform.

AWT is the foundation upon which Swing is made i.e Swing is a set of GUI interfaces that
extends the AWT. But now a days AWT is merely used because most GUI Java programs are
implemented using Swing because of its rich implementation of GUI controls and light-
weighted nature.

Java AWT Hierarchy

23
Component class:
Component class is at the top of AWT hierarchy. Component is an abstract class that
encapsulates all the attributes of visual component. A component object is responsible for
remembering the current foreground and background colors and the currently selected text font.

Container: Container is
a component in AWT that contains another component like button, text field, tables
etc. Container is a subclass of component class. Container class keeps track of components
that are added to another component.

Panel:
Panel class is a concrete subclass of Container. Panel does not contain title bar, menu
bar or border. It is container that is used for holding components.

Window class:
Window class creates a top level window. Window does not have borders and menu
bar.

Frame:
Frame is a subclass of Window and have resizing canvas. It is a container that contain
several different components like button, title bar, textfield, label etc. In Java, most of the AWT
applications are created using Frame window. Frame class has two different constructors,

24
CHAPTER 3
CODING

Frame.java:
package algo_Calc;

import java.awt.EventQueue;

import javax.swing.JFrame;

import javax.swing.JButton;

import java.awt.event.ActionListener;

import java.awt.event.ActionEvent;

public class Frame {

private JFrame frame;

/**

* Launch the application.

*/

public static void main(String[] args) {

EventQueue.invokeLater(new Runnable() {

public void run() {

try {

Frame window = new Frame();

window.frame.setVisible(true);

25
} catch (Exception e) {

e.printStackTrace();

});

/**

* Create the application.

*/

public Frame() {

initialize();

/**

* Initialize the contents of the frame.

*/

private void initialize() {

Sortingss obj = new Sortingss();

frame = new JFrame();

frame.setBounds(100, 100, 456, 324);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.getContentPane().setLayout(null);

JButton btnNewButton = new JButton("Bubble Sort");

btnNewButton.addActionListener(new ActionListener() {

26
public void actionPerformed(ActionEvent e) {

obj.vis(1,"BUBBLE SORT");

frame.setVisible(false);

});

btnNewButton.setBounds(43, 48, 128, 25);

frame.getContentPane().add(btnNewButton);

JButton btnNewButton_1 = new JButton("Insertion Sort");

btnNewButton_1.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

obj.vis(4,"INSERTION SORT");

frame.setVisible(false);

});

btnNewButton_1.setBounds(253, 48, 128, 25);

frame.getContentPane().add(btnNewButton_1);

JButton btnNewButton_2 = new JButton("Selection Sort");

btnNewButton_2.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

obj.vis(2,"SELECTION SORT");

frame.setVisible(false);

});

btnNewButton_2.setBounds(43, 116, 128, 25);

27
frame.getContentPane().add(btnNewButton_2);

JButton btnNewButton_3 = new JButton("Merge Sort");

btnNewButton_3.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

obj.vis(5,"MERGE SORT");

frame.setVisible(false);

});

btnNewButton_3.setBounds(253, 116, 128, 25);

frame.getContentPane().add(btnNewButton_3);

JButton btnNewButton_4 = new JButton("Quick Sort");

btnNewButton_4.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

obj.vis(3,"QUICK SORT");

frame.setVisible(false);

});

btnNewButton_4.setBounds(43, 178, 128, 25);

frame.getContentPane().add(btnNewButton_4);

JButton btnNewButton_5 = new JButton("Max Heap Sort");

btnNewButton_5.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

obj.vis(6,"HEAP SORT");

28
frame.setVisible(false);

});

btnNewButton_5.setBounds(253, 178, 128, 25);

frame.getContentPane().add(btnNewButton_5);

Sortings.java

package algo_Calc;

import java.awt.EventQueue;

import javax.swing.JFrame;

import javax.swing.JTextField;

import javax.swing.JLabel;

import javax.swing.JButton;

import java.awt.event.ActionListener;

import java.awt.event.ActionEvent;

import javax.swing.JTextArea;

import java.awt.Font;

import java.awt.Color;

//import java.awt.Desktop;

29
//import java.io.File;

//import java.io.IOException;

class quiks

void quickSort(int[] num, int start, int end)

int partition = partition(num, start, end);

if(partition-1>start)

quickSort(num, start, partition - 1);

if(partition+1<end)

quickSort(num, partition + 1, end);

int partition(int[] num, int start, int end){

int pivot = num[end];

for(int i=start; i<end; i++){

if(num[i]<pivot){

int temp= num[start];

num[start]=num[i];

num[i]=temp;

30
start++;

int temp = num[start];

num[start] = pivot;

num[end] = temp;

return start;

class merg{

void merge(int num[], int l, int m, int r)

int i, j, k;

int n1 = m - l + 1;

int n2 = r - m;

int[] L = new int[n1];

int[] R = new int[n2];

//int L[n1], R[n2];

31
for (i = 0; i < n1; i++)

L[i] = num[l + i];

for (j = 0; j < n2; j++)

R[j] = num[m + 1+ j];

i = 0; // Initial index of first subarray

j = 0; // Initial index of second subarray

k = l; // Initial index of merged subarray

while (i < n1 && j < n2)

if (L[i] <= R[j])

num[k] = L[i];

i++;

else

num[k] = R[j];

j++;

k++;

while (i < n1)

32
num[k] = L[i];

i++;

k++;

while (j < n2)

num[k] = R[j];

j++;

k++;

void mergeSort(int num[], int l, int r)

if (l < r)

int m = l+(r-l)/2;

mergeSort(num, l, m);

mergeSort(num, m+1, r);

merge(num, l, m, r);

33
class heaps{

void heapify(int num[], int size, int i)

int largest = i;

int left = 2*i + 1;

int right = 2*i + 2;

if (left < size && num[left] >num[largest])

largest = left;

if (right < size && num[right] > num[largest])

largest = right;

if (largest != i)

int temp;

temp = num[i];

num[i]= num[largest];

num[largest] = temp;

heapify(num, size, largest);

34
void heapSort(int num[], int size)

int i;

for (i = size / 2 - 1; i >= 0; i--)

heapify(num, size, i);

for (i=size-1; i>=0; i--)

int temp;

temp = num[0];

num[0]= num[i];

num[i] = temp;

heapify(num, i, 0);

public class Sortingss {

private JFrame frame;

private JTextField textField;

int key;

String tname = new String();

/**

* Launch the application.

35
*/

public static void main(String[] args) throws Exception{

EventQueue.invokeLater(new Runnable() {

public void run() {

try {

Sortingss window = new Sortingss();

window.frame.setVisible(true);

} catch (Exception e) {

e.printStackTrace();

});

/**

* Create the application.

*/

public Sortingss() {

initialize();

public int vis(int k,String str){

key=k;

tname="Hello";

tname="pop";

tname=str;

frame.setVisible(true);

36
return 0;

/**

* Initialize the contents of the frame.

*/

private void initialize() {

frame = new JFrame();

frame.setBounds(100, 100, 514, 329);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.getContentPane().setLayout(null);

JTextArea textArea_1 = new JTextArea();

textArea_1.setFont(new Font("Arial", Font.BOLD, 26));

textArea_1.setBackground(Color.DARK_GRAY);

textArea_1.setForeground(Color.WHITE);

textArea_1.setBounds(102, 0, 304, 41);

frame.getContentPane().add(textArea_1);

textField = new JTextField();

textField.setBounds(102, 102, 304, 22);

frame.getContentPane().add(textField);

37
textField.setColumns(10);

JLabel lblEnterInput = new JLabel("Enter Input");

lblEnterInput.setBounds(30, 105, 85, 16);

frame.getContentPane().add(lblEnterInput);

JTextArea textArea = new JTextArea();

textArea.setLineWrap(true);

textArea.setEditable(false);

textArea.setBounds(102, 175, 304, 56);

frame.getContentPane().add(textArea);

JButton btnSubmit = new JButton("Submit");

btnSubmit.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e){

String fin = new String();

String str=new String();

str = textField.getText();

String [] tok = str.split(" ");

int [] num = new int[tok.length];

for(int i=0;i<tok.length;i++){

num[i]=Integer.parseInt(tok[i]);

38
if(key==1)

int j;

boolean flag = true; // set flag to true to


begin first pass

int temp; //holding variable

while ( flag )

flag= false; //set flag to false awaiting


a possible swap

for( j=0; j < num.length -1; j++ )

if ( num[ j ] > num[j+1] ) // change to


> for ascending sort

temp = num[ j ];
//swap elements

num[ j ] = num[ j+1 ];

num[ j+1 ] = temp;

flag = true; //shows a


swap occurred

fin = "Bubble Sort =";

if(key==2){

39
int n = num.length;

// One by one move boundary of unsorted subarray

for (int i = 0; i < n-1; i++)

// Find the minimum element in unsorted array

int min_idx = i;

for (int j = i+1; j < n; j++)

if (num[j] < num[min_idx])

min_idx = j;

// Swap the found minimum element with the


first

// element

int temp = num[min_idx];

num[min_idx] = num[i];

num[i] = temp;

tname="SELECTION SORT";

fin = "Selection Sort =";

if(key==3){

quiks obj2 =new quiks();

int size=num.length;

40
obj2.quickSort(num,0,size-1);

fin="Quick Sort =";

tname="QUICK SORT";

if(key==4){

int i, ke, j;

for (i = 1; i < tok.length; i++)

ke = num[i];

j = i - 1;

/* Move elements of arr[0..i-1], that are

greater than key, to one position ahead

of their current position */

while (j >= 0 && num[j] > ke)

num[j + 1] = num[j];

j = j - 1;

num[j + 1] = ke;

tname="INSERTION SORT";

fin = "Insertion Sort =";

if(key==5){

41
merg obj3=new merg();

int size =num.length-1;

obj3.mergeSort(num, 0, size);

fin ="Merge Sort =";

tname="MERGE SORT";

if(key==6){

heaps obj4=new heaps();

int size;

size=tok.length;

obj4.heapSort(num,size);

fin ="Heap Sort =";

tname="HEAP SORT";

String str1[] =new String[tok.length];

for(int i=0;i<tok.length;i++){

str1[i]=Integer.toString(num[i]);

fin=fin+" "+str1[i];

textArea.setText(fin);

textArea_1.setText(tname);

});

btnSubmit.setBounds(210, 137, 97, 25);

42
frame.getContentPane().add(btnSubmit);

JLabel lblIntegerMustBe = new JLabel("Integer must be space


separated in your input");

lblIntegerMustBe.setFont(new Font("Arial Black", Font.PLAIN,


14));

lblIntegerMustBe.setBounds(29, 48, 408, 41);

frame.getContentPane().add(lblIntegerMustBe);

JLabel lblYourOutput = new JLabel("Your Output");

lblYourOutput.setBounds(30, 178, 112, 16);

frame.getContentPane().add(lblYourOutput);

JButton btnExit = new JButton("Exit");

btnExit.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

frame.setVisible(false);

});

btnExit.setBounds(210, 244, 97, 25);

frame.getContentPane().add(btnExit);

JButton btnOpenCode = new JButton("Open Code");

btnOpenCode.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e){

if(key==1)

43
try{

ProcessBuilder pb= new


ProcessBuilder("Notepad.exe","bubble.txt");

pb.start();

}catch(Exception ew){

System.out.println(ew.toString());

//C:\\Users\\HARSH\\workspace\\Selection.txt

if(key==2){

try{

ProcessBuilder pb= new


ProcessBuilder("Notepad.exe","selection.txt");

pb.start();

}catch(Exception ew){

System.out.println(ew.toString());

if(key==3){

try{

ProcessBuilder pb= new


ProcessBuilder("Notepad.exe","quicksort.txt");

pb.start();

}catch(Exception ew){

System.out.println(ew.toString());

44
}

if(key==4){

try{

ProcessBuilder pb= new


ProcessBuilder("Notepad.exe","insertion.txt");

pb.start();

}catch(Exception ew){

System.out.println(ew.toString());

if(key==5){

try{

ProcessBuilder pb= new


ProcessBuilder("Notepad.exe","merge.txt");

pb.start();

}catch(Exception ew){

System.out.println(ew.toString());

if(key==6){

try{

ProcessBuilder pb= new


ProcessBuilder("Notepad.exe","maxheap.txt");

45
pb.start();

}catch(Exception ew){

System.out.println(ew.toString());

});

btnOpenCode.setBounds(372, 244, 97, 25);

frame.getContentPane().add(btnOpenCode;}}

46
Chapter 4
Project flow
Step 1:

Fig 1: Command execution

Step 2:

Fig 2: Main Screen

47
Step 3:

Fig 3. Bubble sort

Step 4:

Fig 4. Heap sort

48
Step 5

Fig 5: Merge sort


Step 6:

Fig 6: Quick sort

49
Step 7:

Fig 7: Insertion sort

Step 8:

Fig 8: Selection Sort

50
Chapter 5.

Conclusion

51
Chapter 6

Reference
1. https://www.studytonight.com/java/java-awt.php
2. https://www.geeksforgeeks.org/analysis-of-algorithms-set-2-asymptotic-analysis/
3. https://www.w3schools.in/data-structures-tutorial/sorting-techniques/
4. https://en.wikipedia.org/wiki/Sorting
5. https://en.wikipedia.org/wiki/Sorting_algorithm#Popular_sorting_algorithms

52

Das könnte Ihnen auch gefallen