1 / 40

Sorting numbers

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

hogan
Download Presentation

Sorting numbers

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  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 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.

  2. 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.

  3. 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 approachStep1 :Read listStep2 : Insert-Sort listStep3 : Print list

  4. 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;. .

  5. 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 {seta[i-1] as current elementwhile (position not found) do if no more elements inserta[i] and report position found }

  6. 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 */} }

  7. 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.

  8. Precedence of operators 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.

  9. 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)

  10. 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.

  11. 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.

  12. 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.

  13. 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++;

  14. 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; }

  15. 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 haveexpr1 = 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.

  16. 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.

  17. 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

  18. 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.

  19. 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.

  20. 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.

  21. Type conversions: cont'd Explicit type conversionsThis is done by using the cast operator. The syntax is :(type-name) expressionThe 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.

  22. 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.

  23. control statement We 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.

  24. Example program public static void main(String arg[]){ int marks=20; if (marks < 40) /* fail */ System.out.println("FAIL");}

  25. 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 statement2statement1 is executed if the condition is satisfied otherwise statement2 is executed.

  26. 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"); }

  27. 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);}

  28. 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");}

  29. The ?: operator Suppose 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.

  30. 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

  31. An example Suppose 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); }

  32. 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);}

  33. Iterations: Loops The 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.

  34. The while - loop • Syntax: while ( expression)statementwhile 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)

  35. 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.

  36. while - loop: example program public 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)}

  37. Positive Decimal to Binary class 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); } } }

  38. do-while do { statements } while (condition); • “statements” execute at least once irrespective of condition

  39. The for - loop The 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.

  40. 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);}

More Related