Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <html>
- <head>
- <title>Ordered</title>
- </head>
- <body>
- <h1> Test Header </h1>
- <script>
- var p = 7,
- vector = [3, 5, 13, 26, 54, 22];
- function isOrdered(array, elementNumber) {
- // Check if the array has enough elements
- if (array.length < elementNumber) {
- return[null, 'Array does not have '+elementNumber+((elementNumber == 1) ? ' element' : ' elements')];
- }
- // Initialize direction
- var direction = null,
- segment = [],
- currentComparition;
- // Loop up to the nth element
- for (var i = 0; i < elementNumber-1; i++) {
- // Compare elements
- if (array[i] < array[i+1]) {
- currentComparition = 'lower';
- } else if (array[i] == array[i+1]) {
- currentComparition = 'equal';
- } else if (array[i] > array[i+1]) {
- currentComparition = 'bigger';
- }
- // Set the direction (if not set)
- if (!direction) {
- if (currentComparition != 'equal') {
- direction = currentComparition;
- }
- }
- // Add the first compared element to the segment
- segment.push(array[i]);
- // Check if direction is kept
- if (direction) {
- // Unordered
- if (direction != currentComparition && currentComparition != 'equal') {
- // Add last element
- segment.push(array[i]);
- return [false, segment];
- }
- }
- }
- // Add last element
- segment.push(array[i]);
- // Return ordered result
- return [true, segment];
- }
- var result = isOrdered(vector, p);
- if (result[0]) {
- document.write('Set is ordered: ' + result[1].join(', '));
- } else {
- if (result[0] === null) {
- document.write(result[1]);
- } else {
- document.write('Set is not ordered');
- }
- }
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement