ArrayList array sorting

I do not ask someone to solve this for me, I just need to push a little, because I have no earthly idea on where to start. All I know is that I have to implement collections in this and have a look.

Write a longestSortedSequence method that returns the length of the longest sorted sequence in a list of integers. For example, if a variable called a list stores the following sequence of values:

[1, 3, 5, 2, 9, 7, -3, 0, 42, 308, 17] 

then the call: list.longestSortedSequence () will return 4 because it is the length of the longest sorted sequence in this list (sequence -3, 0, 42, 308). If the list is empty, your method should return 0. Note that for a non-empty list, the method will always return a value of at least 1, because any single element is a sorted sequence.

 Assume you are adding to the ArrayIntList class with following fields: public class ArrayIntList { private int[] elementData; private int size; // your code goes here } 
+6
source share
4 answers

Iterate the array and increment the counter variable if the next element you are processing is larger than the last.

If the next element is smaller or the end of the array is reached, save the current counter value, if it is greater than the current stored maximum value, and reset the counter variable from 0.

+3
source

Pseudocode:

 Variable X: first item of list Variable Y: length of sequence (initial: 1) Variable Z: max length occurred (initial: 0) Loop over the list starting from 2nd index if item is higher than X set X to item add 1 to Y else if Y is higher than Z set Z to Y end if set X to item set Y to 1 end if End-Loop 

This method will restart the counter each time the sequence "reloads", otherwise: it will no longer be sorted. While the list is sorted, it just adds 1 for each item that is in sorted order.

When a sequence ceases to be ordered, it checks whether the current sequence is longer than the longest length of the sequence. If so, you have a new long sequence.

+2
source

Have you thought about for and if else loops? I hope this does not go away. think of one element at a time.

+1
source

Scroll through the array and compare element i with element i+1 . Make a counter. As long as i less than i+1 increments the counter, when i greater than i+1 reset the counter.

0
source

Source: https://habr.com/ru/post/954641/


All Articles