40
Sorting numbers Arrange a list of n numbers a1, a2, a3, ..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion sort works as follows: we look at the numbers one by one, maintaining the numbers already seen in sorted order. Each new number is inserted into its proper place in this sorted list so that the sorted order is preserved.

Sorting numbers Arrange a list of n numbers a1, a2, a3,..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion

Embed Size (px)

Citation preview

Page 1: Sorting numbers Arrange a list of n numbers a1, a2, a3,..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion

Sorting numbers

Arrange a list of n numbers a1, a2, a3, ..., an in ascending order.

A solution: Using Insertion sort.

What is Insertion sort?

Insertion sort works as follows: we look at the numbers one by one, maintaining the numbers already seen in sorted order. Each new number is inserted into its proper place in this sorted list so that the sorted order is preserved.

Page 2: Sorting numbers Arrange a list of n numbers a1, a2, a3,..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion

A solution: cont'd.

Suppose the given list of numbers is 5, 7, -3, 2, 20.

Following the idea above, we obtain the following sorted lists incrementally:

5 ( after inserting 5 into its proper place in an empty list !) 5, 7 (after inserting 7 ...)-3, 5, 7 (after inserting -3 ...)-3, 2, 5, 7 (after inserting 2...)-3, 2, 5, 7, 20 (after inserting 20....)

Finally, we obtain a sorted list of all the numbers.

Page 3: Sorting numbers Arrange a list of n numbers a1, a2, a3,..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion

A program for insertion sort

We address the problem of designing a program for insertion sort. The approach that we shall adopt is one of handling complexity by adding details incrementally. This is popularly known as the top-down or stepwise refinement approach to programming.

A first cut in a top-down approach

Step1 : Read listStep2 : Insert-Sort listStep3 : Print list

Page 4: Sorting numbers Arrange a list of n numbers a1, a2, a3,..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion

A program for insertion sort: cont'd.

• Top-down approach : A second cut

. .Step 2 :

for i = 1 to n do insert a[i] into sorted(a[1], a[2], ..., a[i-1]), by linear search from the high-end; .

.

Page 5: Sorting numbers Arrange a list of n numbers a1, a2, a3,..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion

A program for insertion sort: cont'd.

Top-down approach: A third cut

To insert a[i]| we first claim space for it to the right of a[i-1]| and propagate it to left if necessary.

Step 2: for i = 2 to n do {set a[i-1] as current element while (position not found) do if no more elements insert a[i] and report position found

}

Page 6: Sorting numbers Arrange a list of n numbers a1, a2, a3,..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion

Full-fledged program class insertion_sort{ public static void main(String arg[])

{ int n=8; /* number of elements to sort */ int i, j; /* loop counters */ int key; /* element to insert */ int a[]={0,5,-1,2,8,7,3,6}; /* initialize the list */for (j=1; j<n; j++) /* initialize while-loop variables */ { key = a[ j ]; i=j-1; while (i >= 0 && a[ i ] > key)

{ a[i+1] = a[ i ]; i = i - 1; }

/* find the correct position of key a[j], in the sorted list a[0],... ,a[j-1] */ a[i+1] = key; /* insert key in the correct position */

} for (i=0; i<n; i++) System.out.println(a[i]);/* print the sorted list */

}}

Page 7: Sorting numbers Arrange a list of n numbers a1, a2, a3,..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion

Operators, Expressions, and Statements

Operators allow us to manipulate the data represented by constants and variables

Arithmetic operators: +, *, /, -, %.

The first four are the familiar plus, product, division, subtraction; while the last is themodulus operator - a % b gives the remainder in the division of a by b.

Page 8: Sorting numbers Arrange a list of n numbers a1, a2, a3,..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion

Operators are used with variables and constants to build up expressions. For example, a + b - 2 is an expression. In the presence of several operators in any expression, the rules that tell us the order in which to do the operations are called precedence rules.

The precedence of binary +, - are the same; so are those of *, /, %; the unary + and - also have the same precedence. The first group has lower precedence than the second which in turn have lower precedence than the third.

In cases of equal precedence, arithmetic operators associate from left to right. With these rules, the expression 2 * 3 - 4evaluates to 2 instead of -2.

Precedence of operators

Page 9: Sorting numbers Arrange a list of n numbers a1, a2, a3,..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion

Relational & Equality Operators

Relational : <, <=, >

Equality : ==, !=

Equality operators have higher precedence than relational but lower than arithmetic operators.

Evaluation of the expression 2 < 3 != 5 gives us 0 (which is the value of false)

Page 10: Sorting numbers Arrange a list of n numbers a1, a2, a3,..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion

Logical operators

The relational operators give us relational expressions which are combined using the logical operators: and (&&), or (||), not (!)

For example, in the expression i >= 0 && a[ i] > keyprecedence order is >=, >, &&

The precedence of || is lower than that of &&; while both have lower precedence than the equality operators.

The unary operator ! converts a non-zero operand true into false ( 0), and a 0 operand into 1.

Page 11: Sorting numbers Arrange a list of n numbers a1, a2, a3,..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion

Operators: cont'd

Increment operator ++:it is a unary operator which can be prefixed or suffixed to its

operand. The effect is to increase the value of itsoperand by 1. Thus the effect of both ++n and n++ is to increase n by 1.

Decrement operator - -:it is a unary operator which can be prefixed or suffixed to its

operand. The effect is to decrease the value of itsoperand by 1. Thus the effect of both --n and n-- is to decrease n by 1.

Page 12: Sorting numbers Arrange a list of n numbers a1, a2, a3,..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion

Expressions

An expression is made up of variables, constants and operators.

An arithmetic expression evaluates to a numerical value. A boolean expression is either a relational expression or a logical expression that evaluates to true or false.

For example, if a, b, c are all of type int then a + b - c is an arithmetic expression,

a != b is a relational one and (a < b) && (b > c) is a logical expression.

Page 13: Sorting numbers Arrange a list of n numbers a1, a2, a3,..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion

statements A statement causes an action to be carried out.

Statements are either expression statements, compound statements or control statements.

Expression statement:This is an expression, terminated by a semicolon.

For example:a = 3; c = a + b; n++;

Page 14: Sorting numbers Arrange a list of n numbers a1, a2, a3,..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion

statements: cont'd.

Compound statements:These consist of several statements

enclosed with a pair of braces For example: while (i >= 0 && a[i] > key)

{ a[i+1] = a[i]; i = i - 1; }

Page 15: Sorting numbers Arrange a list of n numbers a1, a2, a3,..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion

Operators Once More

Assignment operator: This has the form op=.

The assignment expression n = n + 2 can be written as n += 2.As such n and 2 become the operands of the operator +=.In general, if op is a binary operator, we have expr1 = expr1 op expr2,which can be written as expr1 op= expr2so that expr1 and expr2 are the operands of the operator op= which we call the assignment operator.

Page 16: Sorting numbers Arrange a list of n numbers a1, a2, a3,..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion

Precedence among operators

Operators Associativity ( ) [ ] left to right ! ++ -- + - * type sizeof right to left * / % left to right + - left to right < <= > >= left to right == != left to right && left to right || left to right ? : right to left = += -= *= /= %= left to right

The precedence decreases from the top to thebottom of the table.

Page 17: Sorting numbers Arrange a list of n numbers a1, a2, a3,..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion

Operator precedence• What is the answer? (assume x=1)

x*x+x%2

2*x/2%4 (need to know associativity)

• Almost all operators are left associative– This indicates in which direction the operators

of the same precedence will evaluate– Assignment has right associativity

x=y=2; // assigns y=2 first and then x=y– The above expression would lead to wrong

answer if assignment was left associative

Page 18: Sorting numbers Arrange a list of n numbers a1, a2, a3,..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion

Type conversions

The constituent variables and constants in an expression can be of different types. Then the question that naturally arises is what is the type of the value of an expression.

For example, if in the expression a + b, a is of type int and b is of type float, then what is the type of the sum?

Type conversion rules tell us what should be the type of the sum. We address these questions in the next couple of slides.

Page 19: Sorting numbers Arrange a list of n numbers a1, a2, a3,..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion

Type conversions: cont'd.

Implicit type conversionsSuch conversions take place in several contexts.

In arithmetic operations:When operands of an arithmetic operator have different

types.For example, if a is of type int and b is of type char then the type of the result of a + b is int.

The general rule here is that 'a lower' type is elevated to 'a higher' type.

Page 20: Sorting numbers Arrange a list of n numbers a1, a2, a3,..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion

Type conversions: cont'd.

Across assignments:In an assignment expression the right-hand side is first

evaluated; the returned value is the value of the left-hand side and also the value of the assignment expression. The type of the left-hand side and that of the assignment expression is the type of the right hand side.

For example,if x is of type int and i is of char then as a result of the assignment x = i, x becomes of type char.

Page 21: Sorting numbers Arrange a list of n numbers a1, a2, a3,..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion

Type conversions: cont'd

Explicit type conversions This is done by using the cast operator. The syntax is :(type-name) expression

The meaning is that the type of the expression is changed to the type specified within round-brackets. For example,

sin((float) n)

converts the value of n to type float before passing it on to sin.

Page 22: Sorting numbers Arrange a list of n numbers a1, a2, a3,..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion

The execution flow

The execution of any program starts from the first line of the program and proceeds sequentially downwards.

For example, if a program has ten assignment statements, these would be executed in order of their appearance.

However, in most of the programs that we would like to write,we would want to execute some statements only if some condition holds.

For example, a program that takes as input marks between 0 and 100, and outputs FAIL if the marks are less than 40.

Page 23: Sorting numbers Arrange a list of n numbers a1, a2, a3,..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion

control statementWe use the if control statement to achieve this.

The syntax of an if statement is:

if ( condition) statement

The statement is executed only if the conditional expression condition is true, otherwise the control goes to the statement following the if statement.

Note that the statement may actually be a compoundstatement, or a control statement, or a combination.

Page 24: Sorting numbers Arrange a list of n numbers a1, a2, a3,..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion

Example program

public static void main(String arg[]){ int marks=20;

if (marks < 40) /* fail */ System.out.println("FAIL");}

Page 25: Sorting numbers Arrange a list of n numbers a1, a2, a3,..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion

The if-else statement

When, depending on a condition, we want to execute onestatement block or other, we use if-else statement.

Its syntax is: if ( condition)

statement1 else

statement2

statement1 is executed if the condition is satisfied otherwise statement2 is executed.

Page 26: Sorting numbers Arrange a list of n numbers a1, a2, a3,..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion

Example

public static void main(String arg[]) { int marks =20; if ((marks < 0) || (marks > 100)) System.out.println("Out of range!"); else if (marks < 40) /* fail */ System.out.println("FAIL"); else /* pass */ System.out.println("PASS"); }

Page 27: Sorting numbers Arrange a list of n numbers a1, a2, a3,..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion

Example

public static void main(String arg[]){ int a, b; a=2;

b=3; System.out.println("Larger number is "); if (a > b) System.out.println("", a); else System.out.println("", b);}

Page 28: Sorting numbers Arrange a list of n numbers a1, a2, a3,..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion

if-else ladder

public static void main(String arg[]){

int marks; marks=60; if ((marks < 0) || (marks > 100))

System.out.println("Out of range!"); else if (marks < 40) /* fail */ System.out.println("Grade: F"); else if (marks < 70) System.out.println("Grade: B"); else System.out.println("Grade: A");}

Page 29: Sorting numbers Arrange a list of n numbers a1, a2, a3,..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion

The ?: operatorSuppose we want to assign different values to a

variable depending upon whether some condition is true or not.One way to do it is, of course, using an if-else statement.There is another, more concise, way of doing this via the ?: operator.The syntax of the operator is:

condition ? expn-1 : expn-2

The above expression returns the value of expression expn-1 if the conditional expression condition evaluates to true, otherwise returns the value of expn-2.

Page 30: Sorting numbers Arrange a list of n numbers a1, a2, a3,..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion

More on ‘+’ operator

+ operator can be used both as concatenation as well as for arithmetic addition depending on the context.

Example:

String s =“ajai” + “ jain” ; //concatenate ajai and jain

String s = “ajai” +1955;//concatenate ajai and 1955

int i = ‘a’+3; // Arithmetic addition

Page 31: Sorting numbers Arrange a list of n numbers a1, a2, a3,..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion

An exampleSuppose that there were only two rates of taxes:

No tax for income less than or equal to 150,000 and a flat rate of 10% above it.

Then the tax calculation program is:public static void main(String arg[]){ int income; float tax; income=120000;

tax = (income <= 150000)? 0.0 : (income - 150000)*0.1;

System.out.println ("tax= %f", tax);}

Page 32: Sorting numbers Arrange a list of n numbers a1, a2, a3,..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion

Correct but not advised example

public static void main(String arg[]){ int income; float tax; income=350000;

tax = (income <= 150000) ? 0.0 : ((income <= 300000) ? (income - 150000) * 0.10 : ((income <= 500000) ? 15000 + (income - 300000) * 0.2 : 55000 + (income - 500000) * 0.3))); System.out.println ("tax= %f", tax);

}

Page 33: Sorting numbers Arrange a list of n numbers a1, a2, a3,..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion

Iterations: LoopsThe computational power of a machine is exploited

at the program level by means of constructs that repeat a set of actions again and again until some conditions are satisfied.

For example, in the Insertion-sort program we repeatedly take a new element from the unsorted list, and insert it into its proper place among the elements already seen and kept in sorted order.

Or consider evaluating the sine of a quantity x by using the power series expansion of sin x.

C has several repetitive constructs, like the for- loop, the while- loop etc.

Page 34: Sorting numbers Arrange a list of n numbers a1, a2, a3,..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion

The while - loop• Syntax:

while ( expression) statement

while is a key word, expression and statement are programmer-defined.

• Meaning of the construct:

The statement is executed as long as expression evaluates to true (non-zero value)

Page 35: Sorting numbers Arrange a list of n numbers a1, a2, a3,..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion

while loop: Example

. . while (i >= 0 && a[i] > key) { a[i+1] = a[i]; i = i - 1; }

. . This while- loop had been used in the Insertion-sort program discussed earlier.

Page 36: Sorting numbers Arrange a list of n numbers a1, a2, a3,..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion

while - loop: example programpublic static void main(String arg[])

{ int sum, n;

sum = 0; n=523;

while (n != 0){ sum += n % 10;

n /= 10; }

System.out.println("The sum of the digits is = ", sum)

}

Page 37: Sorting numbers Arrange a list of n numbers a1, a2, a3,..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion

Positive Decimal to Binaryclass positiveDecimalToBinary { public static void main(String arg[]) { int n = 34, y=0, polyTerm = 1; if (n < 0) { System.out.println(“Sorry, cannot handle negative

integers today!”); } else { while (n > 0) { y += (polyTerm*(n%2)); n /= 2; polyTerm *= 10; } System.out.println(“Required binary: ” + y); } }}

Page 38: Sorting numbers Arrange a list of n numbers a1, a2, a3,..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion

do-whiledo {

statements

} while (condition);

• “statements” execute at least once irrespective of condition

Page 39: Sorting numbers Arrange a list of n numbers a1, a2, a3,..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion

The for - loopThe syntax:

for ( expr1; expr2; expr3) statement

Meaning of the construct:

The initialization of the loop-control variable is done by means of the expression expr1; the second expression expr2 controls the number of times the statement that follows is executed; the third expression expr3 updates the loop control variable after each execution of the statement.

Page 40: Sorting numbers Arrange a list of n numbers a1, a2, a3,..., an in ascending order. A solution: Using Insertion sort. What is Insertion sort? Insertion

for-loop: sum of first n positive numbers public static void main(String arg[])

{ int n, i; long sum; /*sum is a long integer*/n=20;

sum = 0; for(i = 1; i <= n; i++) sum += i; System.out.println("The sum is =", sum);}